如何创建包含多个所选项目的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 });
但似乎没有将多个项目设置为已选中。我怎么能这样做?
答案 0 :(得分:4)
您无法使用SelectList
您需要使用MultiSelectList并按照以下方式使用它:
public MultiSelectList(
IEnumerable items,
string dataValueField,
string dataTextField,
IEnumerable selectedValues
)
您还可以查看this SO answer