Asp.net MVC how to populate dropdown list with numbers

user1781232 picture user1781232 · Apr 15, 2015 · Viewed 15.3k times · Source

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>

Answer

Chris Pratt picture Chris Pratt · Apr 15, 2015

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.