Pass value from Select html to Controller via Post

1

I have a form where I pass some fields via Helper.

Ex:

<divclass="form-group col-md-6">
     @Html.LabelFor(model => model.Nome, new { @class = "control-label col-md- 6" })
     @Html.EditorFor(model => model.Email, new { htmlAttributes = new { @class   = " form-control", @placeholder = "Digite um Nome" } })
     @Html.ValidationMessageFor(model => model.Nome)
</div>

So far, I still have a SELECT :

<div class="row">
    <div class="form-group col-md-3">
    @Html.Label("Pais", new { @class = "col-md-3" })
    <select id="cmbPais" class="form-control">
    <option>Carregar Paises</option>
    </select>
    </div>
    <div class="form-group col-md-4">
    @Html.Label("Estado", new { @class = "col-md-3" })
    <select id="cmbEstado" class="form-control">
    <option>Carregar Estados</option>
    </select>

<div class="form-group col-md-4">
     @Html.Label("Cidade", new { @class = "col-md-3" })
      <select id="cmbCidade" class="form-control">
      <option>Carregar Cidades</option>
   </select>
  </div>
 </div>
</div>

where I need to pass the selected value to the controller to register the user. How can I do this ?

    
asked by anonymous 01.03.2016 / 21:16

2 answers

1

How are you loading the list of cities?

If the CityId exists in your Model, you can replace the select attribute with the HtmlHelper DropDownFor , like this:

@Html.DropDownListFor(model => model.CidadeId, <sua lista>, "Carregar Cidades")

Razor will thus create a select attribute with all options passed in the second parameter list, as well as bind to your model property.

Explaining the parameters:

  • The first parameter will store the value that is selected in the list.
  • The second parameter will be your list. Note that it is of the type IEnumerable<SelectListItem> so if you load it on Controller , it must be this type. If you upload via jQuery (only including options in select attribute), do not worry with this property and just pass new List<SelectListItem>() .
  • The third parameter is the value to display if no item is selected.

If you do not have CiudadId in your model, use the HtmlHelper DropDownList " instead, in this way:

 @Html.DropDownList("CidadeId",  <sua lista>, "Carregar Cidades")

So, just create a parameter named CidadeId in POST of your Controller and it will pass the selected value to this parameter

    
02.03.2016 / 14:38
2

If you want to pass CidadeId to Controller , using the appropriate variable name already does this for you:

<select id="CidadeId" class="form-control">
    <option>Carregar Cidades</option>
</select>

Or you can use Razor:

@Html.DropDown("CidadeId", /* Coloque aqui a lista que populará a DropDown */)
    
01.03.2016 / 21:55