使用 MVC DropDownList 帮助器可以让您免于写出所有 html。下面是在视图中设置选项值的示例。
<div class="col-md-10">
@Html.DropDownListFor(model => model.NumberParticipant,
new SelectList(new []
{ new {value="",text=""},
new {value="2",text="2"},
new {value="3",text="3"},
new {value="4",text="4"},
new {value="5",text="5"}
},"value","text"), new { htmlAttributes = new { @class = "form-control" }})
</div>
最佳实践是将 SelectList 类型的属性添加到模型类中并在那里设置可能的选项。然后,您可以在助手中引用新属性,如下所示:
<div class="col-md-10">
@Html.DropDownListFor(model => model.NumberParticipant,
Model.MySelectList, new { htmlAttributes = new { @class = "form-control" }})
</div>