用 1 - x 中的数字动态填充 @Html.DropDownList

Dynamically fill @Html.DropDownList with numbers from 1 - x

在视图中我有以下内容:

@Html.DropDownList("numberup", new List<SelectListItem>
{
    new SelectListItem{Text = "1", Value = "1"},
    new SelectListItem{Text = "2", Value = "2"}
}, "Select NumberUp", new { id = "numberup", @class = "form-control", @style = "width: auto; margin: 0 0 25px 0;" })

我想动态创建 select 列表项,而不是一个一个地输入它们。我该怎么做?

使用 Enumerable.Range 构建 SelectListItemlist 并将其分配给您的 DropDownList:

@{
    var list = Enumerable.Range(1, 30).Select(x => x.ToString()).Select(x => new SelectListItem() { Text = x, Value = x }).ToList();
}

@Html.DropDownList("numberup", list, "Select NumberUp", new { id = "numberup", @class = "form-control", @style = "width: auto; margin: 0 0 25px 0;" })

HTH