MVC和Stackoverflow的新手很抱歉没有足够的声誉发布图片......
尝试使用预先选择的值
呈现ListBox我的SQL数据库: http://i.imgur.com/bcdXyqE.png
我的实体框架 http://i.imgur.com/wYWXuAq.png
我的控制器
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
var roles = db.Role;
var newList = new List<SelectListItem>();
foreach (var role in roles)
{
newList.Add(
new SelectListItem()
{
Value = role.Id.ToString(),
Text = role.RoleName,
Selected = user.Role.Contains(role)
}
);
}
ViewBag.x = new SelectList(newList, "Value", "Text");
ViewBag.Roles = new SelectList(db.Role, "Id", "RoleName", user.Role);
return View(user);
}
我的观点
<p>try1:</p>
@Html.ListBox("Roles", null, new { @class = "form-control", @size = 6, @style = "height: initial" })
<p>try2:</p>
@Html.ListBox("x", null, new { @size = 6, @style = "height: initial" })
使用预先选择的值渲染2次尝试中的非?
答案 0 :(得分:0)
让它发挥作用。
public ActionResult AccessRights(int id)
{
var user = db.User.Find(id);
IEnumerable<SelectListItem> roles = db.Role.Select(c => new SelectListItem{ Value = c.Id.ToString(), Text = c.RoleName, Selected = true});
var rolesSelected = new int[user.Role.Count];
var i = 0;
foreach (var role in user.Role)
{
rolesSelected[i] = role.Id;
i++;
}
ViewBag.Roles = roles.ToList();
ViewBag.RolesSelected = rolesSelected;
return View(user);
}
@Html.ListBox("RolesSelect", new MultiSelectList(ViewBag.Roles, "Value", "Text", ViewBag.RolesSelected), new { @class = "form-control", @size = 6, @style = "height: initial" })