Asp.net MVC how to populate dropdown list with numbers
Asked Answered
E

3

24

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>
Essonite answered 15/4, 2015 at 20:8 Comment(2)
Can you post your model ?Clorindaclorinde
This is close to what you asked. https://mcmap.net/q/581853/-mvc3-dropdownlistforResting
K
64

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.

Kenning answered 15/4, 2015 at 20:34 Comment(0)
C
4

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" })
Coil answered 29/12, 2016 at 10:39 Comment(0)
F
0

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.

Freak answered 1/9, 2020 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.