在PostBack上设置多个SelectList值

时间:2016-09-01 11:38:33

标签: c# asp.net-mvc asp.net-mvc-5 bootstrap-selectpicker

我有一个包含多个选择列表的表单,我也使用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>

发布时:

enter image description here

每次发布​​列表都是空的。 列表名称与模型属性名称匹配。

我错过了什么?

我有一个单一选择的列表,所以选择的值是一个简单的字符串,这很好,但上面给我一个头疼。

1 个答案:

答案 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属性应为ArrayIEnumerable<int>IList<int>以绑定更正。 (ofcource不仅可以int,还可以stringbool等。)

如果您正在寻找获得最佳方法,我建议您使用强类型助手 - ListBoxFor

@Html.ListBoxFor(x => x.SystemTypeIds
               ,RegistrationHandlers.GetSystemtypes()
               ,new { @class = "form-control", @title = "---  Välj Systemtyp  ---" })