1

最終的解決:

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 ?)

もっと簡単な方法である必要がありますか?

4

3 に答える 3

4

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-19T09:04:01.023 に答える
0

にはオブジェクトのリストが含まれており、それぞれにプロパティSelectListがあります。したがって、次のようなことができます。SelectListItemSelected

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;
于 2013-02-19T09:04:31.193 に答える