简体   繁体   English

Asp.net MVC 如何用数字填充下拉列表

[英]Asp.net MVC how to populate dropdown list with numbers

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.我见过类似的例子,人们需要用对象列表填充,但我想要实现的只是在我的 DropdownlistFor 中包含数字 1-10。 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.所有这些都是创建一个 1 到 10 之间的整数的可枚举,然后使用一点 LINQ 将其转换为Html.DropDownListFor可以接受的IEnumerable<SelectListItem>

Years list from current year to n years back.从当前年份到 n 年前的年份列表。

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:对于较新版本的 ASP Mvc 或 Asp Core,您可以使用以下内容:

<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.这是我用来将 int 值绑定到模型的方法。 DropDownListFor expects a IEnumerable<SelectListItem> which you don't need for a simple number dropdown. DropDownListFor 需要一个 IEnumerable<SelectListItem> ,您不需要简单的数字下拉列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM