最终解决方案:
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
@Html.ListBoxFor(x => x.SelectedRoles, Model.DropDownRoles)
==========================
我有一个下拉列表来显示用户角色,如下所示:
HTML
@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 ?)
必须是更简单的方法吗?