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>
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" })
For newer versions of ASP Mvc or Asp Core you can use something like:
<input type="number" asp-for="NumberOfTickets" class="form-control" placeholder="Number of Tickets" min="1" max="10" />
Complete code would be:
<div class="form-group">
@Html.LabelFor(model => model.NumberOfTickets, new { @class = "control-label col-md-2" })
<div class="col-md-10">
<input type="number" asp-for="NumberOfTickets" class="form-control" placeholder="Number of Tickets" min="1" max="10" />
@Html.ValidationMessageFor(model => model.NumberOfTickets)
</div>
This is what I use to bind an int value to the model. DropDownListFor expects a IEnumerable<SelectListItem> which you don't need for a simple number dropdown.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.