public ActionResult Edit(int? id)
{
ViewBag.Role = new SelectList((from t in db.Roles where t.RoleID != 1 && t.RoleID != 2 select t), "RoleID", "RoleName");
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
User user = db.Users.Find(id);
if (user == null)
{
return HttpNotFound();
}
return View(user);
}
ViewBag.Role会将所有Roles Value生成到multiselect复选框中。
<div class="form-group">
@Html.Label("Roles", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("Role", null, htmlAttributes: new { @multiple = "multiple", @class = "form-control" })
</div>
</div>
<script type="text/javascript">
$(function () {
$('#Role').multiselect({
includeSelectAllOption: true
});
});
基本上,MultiSelect CheckBox如下图所示。
这是我的问题,我该如何预先检查用户已经拥有的角色? 例如,x用户具有一个角色Manager,因此在编辑页面中Manager复选框将被选中。
答案 0 :(得分:1)
您可以这样做:
$('select').multiselect({includeSelectAllOption: true});
// Get your data
var userRoles="1,3"; // You can use a ViewBag like ViewBag.UserRoles for roles of user
// Split data by ","
var userRolesArray=userRoles.split(",");
// Set dataArray
$("select").val(userRolesArray);
// Refresh for cheking default values
$("select").multiselect("refresh");
您可以将ViewBag
之类的ViewBag.UserRoles
用作用户角色,并将其填写在Action
中。