ASP.NET MVC中的DropdownList – 未发布值
我在ASP MVC(Razor)中有一个表单,在这个表单中我有一个Textboxes …和一个 ,我想把这个select的选定选项(值)传递给控制器,就像其他信息一样。 文本框正确传输到控制器,它位于数据库中。
我在数据库中有一个名为NumberParticipant的字段,我希望通过我的Create控制器传输数据库:
我的代码:
@using (Html.BeginForm()) { @Html.LabelFor(model => model.LocalNumber, new { @class = "control-label col-md-2" }) @Html.EditorFor(model => model.LocalNumber, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.LocalNumber) 2 3 4 5 }
使用MVC DropDownList帮助程序可以避免写出所有的html。 这是一个在视图中设置选项值的示例。
@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" }})
最佳做法是将SelectList类型的属性添加到模型类,并在那里设置可能的选项。 然后,您可以像这样在助手中引用新属性:
@Html.DropDownListFor(model => model.NumberParticipant, Model.MySelectList, new { htmlAttributes = new { @class = "form-control" }})