I have seen similar examples where people need to populate with a list of object but all I would like to achieve is to have the numbers 1-10 in my DropdownlistFor in my view. Is there a simple way of doing this. Following is what I have.
<div class="form-group">
@Html.LabelFor(model => model.NumberOfTickets, new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownListFor(model => model.NumberOfTickets)
@Html.ValidationMessageFor(model => model.NumberOfTickets)
</div>
</div>
Binding MVC DropDownList with Static Values Just add an Html helper for DropDownList and provide a static list of SelectListItem. The values added as SelectListItem will be added and displayed in the DropDownList. In this way, you do not need to add anything to Controller Action.
Sometimes it our ASP.NET MVC application it becomes necessary to populate dropdown with dynamic values such as from the database. So here in the controller you can create a list object of type SelectListItem, fill it with values and then send this object to the View.
To add a view page, select the respective action method, right click and click on add view option at the top. Inside create.cshtml view page, we have defined a dropdown list control to retrieve data from database and bind it to the dropdown list control.
We have two options to add the items, one is to add its multiple options in the items list directly writing into .aspx page. Secondly, at run time we can add it dynamically or bind via the database. Now we will see how we implement drop down list in asp.net via code.
The above code is to retrieve data from SQL Server database and bind the data to dropdown list control in ASP.NET Core MVC application. The next step is to add a view page for the create action method defined inside the controller class. To add a view page, select the respective action method, right click and click on add view option at the top.
You can use something like the following:
@Html.DropDownListFor(m => m.NumberOfTickets, Enumerable.Range(1, 10).Select(i => new SelectListItem { Text = i.ToString(), Value = i.ToString() }))
All this does is create an enumerable of integers between 1 and 10 and then uses a bit of LINQ to transform it into an IEnumerable<SelectListItem>
that Html.DropDownListFor
can accept.
Years list from current year to n years back.
int startYear = 1980 @Html.DropDownListFor(m => m.DateofEstablishment, Enumerable.Range(0, (DateTime.Now.Year - startYear -1)).Select(i => new SelectListItem { Text = (DateTime.Now.Year - i).ToString(), Value = i.ToString() }), "Please select year", new { @class = "form-control", @required = "required" })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With