DropdownList in ASP.NET MVC - value not published

I have a form in ASP MVC (Razor), and in this form I have text fields ... and <select> , and I want to transfer the selected option (value) of this choice to the controller, like other information, Text fields are transferred correctly to the controller and in the database.

I have a field in the database called NumberParticipant, and I want to transfer the database through my Create controller:

My code is:

 @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" /> } 
+5
source share
1 answer

Using the MVC helper DropDownList will save you from writing all of the html. Here is an example that sets parameter values ​​in a 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> 

It would be best practice to add a property of type SelectList to the model class and set possible options. You can then refer to the new property in the helper as follows:

 <div class="col-md-10"> @Html.DropDownListFor(model => model.NumberParticipant, Model.MySelectList, new { htmlAttributes = new { @class = "form-control" }}) </div> 
+5
source

Source: https://habr.com/ru/post/1209282/


All Articles