具有多个所选项目的SelectList

时间:2013-10-08 09:29:30

标签: c# asp.net-mvc razor multi-select selectlist

如何创建包含多个所选项目的SelectList?我想将SelectList绑定到Razor下拉列表,如果它是一个选定的项目,我正在使用此代码

        List<SchoolApp.Models.Accounts.role> roles = accRepo.GetRoles();
        if (selected > 0)
        {
            ViewBag.RolesList = new SelectList(roles, "Id", "RoleName");
        }
        else
        {
            ViewBag.RolesList = new SelectList(roles, "Id", "RoleName", selected);
        }

在Razor中我使用了语法

   <div class="editor-label">
        @Html.LabelFor(model => model.RoleId)
    </div>

    <div class="editor-field">         
        @Html.DropDownListFor(model => model.RoleId, (SelectList)ViewBag.RolesList, "Select", new { @class = "multiselect", @multiple = "multiple", @style = "width: 450px;height:300px" })
        @Html.ValidationMessageFor(model => model.RoleId)
    </div>

但是如何设置此SelectList上选择的多项?我试过

  ViewBag.RolesList = new SelectList(roles, "Id", "RoleName",, new[] { 2, 3, 10, 11 });

但似乎没有将多个项目设置为已选中。我怎么能这样做?

1 个答案:

答案 0 :(得分:4)

您无法使用SelectList

选择多个项目

您需要使用MultiSelectList并按照以下方式使用它:

public MultiSelectList(
  IEnumerable items,
  string dataValueField,
  string dataTextField,
  IEnumerable selectedValues
)

您还可以查看this SO answer