我有一个包含多个选择列表的表单,我也使用bootstrap selectpicker。
码 :
模型 :
[Display(Name = "SystemTyp")]
[Required(ErrorMessage = "Vänligen välj typ")]
public List<SelectListItem> SystemTypes { get; set; }
视图 :
<div class="form-group">
@Html.Label("SystemTyp", new { @class = "col-md-2 control-label" })
<div class="col-md-10">
@Html.DropDownList("SystemTypes",
RegistrationHandlers.GetSystemtypes()
,
new { @class = "form-control", @multiple = "multiple", @title = "--- Välj Systemtyp ---" })
@Html.ValidationMessageFor(model => model.SystemTypes, "", new { @class = "text-danger" })
</div>
</div>
发布时:
每次发布列表都是空的。 列表名称与模型属性名称匹配。
我错过了什么?
我有一个单一选择的列表,所以选择的值是一个简单的字符串,这很好,但上面给我一个头疼。
答案 0 :(得分:2)
您应该理解DropDownList
帮助者在html标记中创建select
个带name="SystemTypes"
属性的标记。
在 POST 中,使用UserRole
名称传递选定的值。
你不需要POST上的whoule列表,你只需要选择值,所以在SystemTypeId
中创建ViewModel
属性并将你的助手更改为:
@Html.DropDownList("SystemTypeId", <-- note this
RegistrationHandlers.GetSystemtypes()
,
new { @class = "form-control", @multiple = "multiple", @title = "--- Välj Systemtyp ---" })
然后,您将在绑定模型中获得选定的值。
不要试图获得whoulde列表 - 你不需要它。
如果您需要选择 多个 ,则应使用ListBox
帮助:
@Html.ListBox("SystemTypeIds", <-- note this
RegistrationHandlers.GetSystemtypes()
,
new { @class = "form-control", @title = "--- Välj Systemtyp ---" })
SystemTypeIds
属性应为Array
或IEnumerable<int>
或IList<int>
以绑定更正。 (ofcource不仅可以int
,还可以string
,bool
等。)
如果您正在寻找获得最佳方法,我建议您使用强类型助手 - ListBoxFor
:
@Html.ListBoxFor(x => x.SystemTypeIds
,RegistrationHandlers.GetSystemtypes()
,new { @class = "form-control", @title = "--- Välj Systemtyp ---" })