Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DropdownList in ASP.NET MVC - value not posted

I have a form in ASP MVC (Razor) and in this form I have a Textboxes... and a <select> and I want to transmit the selected option (value) of this select to the controller like the other information. The textboxes are transmitted correctly to the controller and it's in the database.

I have a field in the database called NumberParticipant and I want to transmit i tin the database thanks to my Create controller :

My code :

@using (Html.BeginForm())
{
  <div class="form-group">
    @Html.LabelFor(model => model.LocalNumber, new { @class = "control-label col-md-2" })
    <div class="col-md-10">
      @Html.EditorFor(model => model.LocalNumber, new { htmlAttributes = new { @class = "form-control" } })
      @Html.ValidationMessageFor(model => model.LocalNumber)
    </div>
  </div>
  <div class="col-md-10">
    <select class="form-control" id="numberParticipant">
      <option value=""></option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
    </select>
  </div>
  <input type="submit" value="Create" class="btn btn-default" />
}
like image 598
Memo Avatar asked Dec 16 '14 22:12

Memo


1 Answers

Using the MVC DropDownList helper would save you from writing out all the html. Here's an example that sets the option values in the view.

<div class="col-md-10">
    @Html.DropDownListFor(model => model.NumberParticipant, 
        new SelectList(new [] 
        { new {value="",text=""},
          new {value="2",text="2"},
          new {value="3",text="3"},
          new {value="4",text="4"},
          new {value="5",text="5"}
    },"value","text"), new { htmlAttributes = new { @class = "form-control" }})
</div>

A best practice would be to add a property of type SelectList to your model class and set the possible options there. You could then reference the new property in the helper like this:

<div class="col-md-10">
    @Html.DropDownListFor(model => model.NumberParticipant, 
        Model.MySelectList, new { htmlAttributes = new { @class = "form-control" }})
</div>
like image 90
Alain Bates Avatar answered Oct 05 '22 07:10

Alain Bates