最終的解決:
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");
問題は、ドロップダウンで選択した値を設定する方法がわからないことです。ラムダ式を使用して、一致するロールをリストの一番上に配置し、残りをアルファベット順に配置できるのではないかと考えました。
var roles = context.Roles
.ToList()
.OrderBy( ? matching role then other selectable roles ?)
もっと簡単な方法である必要がありますか?