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>
2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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" })

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.