最终解决方案:
public class UpdateUser
{
public IEnumerable<string> SelectedRoles { get; set; }
public IEnumerable<SelectListItem> DropDownRoles { get; set; }
}..。
var roles = context.Roles.Select(x => x.RoleName).ToList();
UpdateUser userToUpdate = new UpdateUser
{
SelectedRoles = user.Roles.Select(x => x.RoleName),
DropDownRoles = new SelectList(roles, user.Roles)
};@Html.ListBoxFor(x => x.SelectedRoles, Model.DropDownRoles)=========================
我有一个液滴来显示这样的用户角色:
@Html.TextBoxFor(x => x.Roles)
@Html.DropDownList( "roles", ViewData["roles"] as SelectList)控制器
var user = context.Users.Include(x => x.Roles).Where(x => x.UserId == id).FirstOrDefault();
ViewData["roles"] = new SelectList(context.Roles, "RoleId", "RoleName");问题是,我无法计算如何在下拉列表中设置选定的值。我想,也许我可以使用Lambda表达式将匹配的角色放在列表的首位,然后按字母顺序排列其余的角色。
var roles = context.Roles
.ToList()
.OrderBy( ? matching role then other selectable roles ?)一定是更简单的方法吗?
发布于 2013-02-19 09:04:01
不要使用与ViewData键和下拉列表所选值相同的值。就像这样:
@Html.DropDownList("selectedRole", ViewData["roles"] as SelectList)然后,POST控制器操作可以将其作为参数:
[HttpPost]
public ActionResult Index(string selectedRole)
{
...
}如果表单中有其他字段,则可以在视图模型中对它们进行分组:
public class MyViewModel
{
public string SelectedRole { get; set; }
public string SomeOtherField { get; set; }
}然后让您的控制器操作,以这个视图模型作为参数。既然现在您有了一个视图模型,那么让我们充分利用它,去掉可怕的弱类型ViewData
public class MyViewModel
{
public string SelectedRole { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
public string SomeOtherField { get; set; }
public string YetAnotherField { get; set; }
}然后,您可以让GET操作填充此视图模型:
public ActionResult Index()
{
var model = new MyViewModel();
model.Roles = new SelectList(context.Roles, "RoleId", "RoleName");
return View(model);
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
...
}然后可以将视图强类型到视图模型:
@model MyViewModel
@using (Html.BeginForm())
{
...
@Html.DropDownListFor(x => x.SelectedRole, Model.Roles)
...
<button type="submit">OK</button>
}发布于 2013-02-19 09:04:31
SelectList包含一个SelectListItem对象列表,每个对象都具有一个Selected属性。所以你可以做这样的事:
var user = context.Users.Include(x => x.Roles).Where(x => x.UserId == id).FirstOrDefault();
var temp = new SelectList(context.Roles, "RoleId", "RoleName");
temp.First(x => x.Value.Equals(IdOfSelectedObject)).Selected = true;
ViewData["roles"] = temp;https://stackoverflow.com/questions/14953447
复制相似问题