2011-01-10 16 views
6

usersrolesのコンテキストでビューとコントローラの多対多オブジェクトマッピングを処理するにはどうすればよいですか?多くのasp.net MVCビューとコントローラ

私はこのような純粋なPOCOSにマップするエンティティフレームワークを使用:私の見解では

public class Role 
{ 
    public int RoleId { get; set; } 
    public string RoleName { get; set; } 
    public List<User> Users { get; set; } 
} 

public class User 
{ 
    public int UserId { get; set; } 
    public List<Role> Roles { get; set; } 
} 

、私はチェックボックスを使用してロールにユーザーを追加したいと思います。私はすべてのロールをリストし、そのロールにユーザーを追加するロールをチェックします。これをどうすれば処理できますか?

答えて

15
私はこのシナリオのためにビューモデルを設計することにより開始する

public class UserRolesViewModel 
{ 
    public int UserId { get; set; } 
    public IEnumerable<RoleViewModel> Roles { get; set; } 
} 

public class RoleViewModel 
{ 
    public int RoleId { get; set; } 
    public bool InRole { get; set; } 
    public string RoleName { get; set; } 
} 

そしてロールコントローラ:

public class RolesController : Controller 
{ 
    public ActionResult Edit(int userId) 
    { 
     // TODO: Use a repository to fetch the roles associated to the given 
     // user id and then AutoMapper to map your model POCOs 
     // to a UserRolesViewModel 
     var model = new UserRolesViewModel 
     { 
      UserId = userId, 
      Roles = new[] 
      { 
       new RoleViewModel { RoleId = 1, InRole = false, RoleName = "Role 1" }, 
       new RoleViewModel { RoleId = 2, InRole = true, RoleName = "Role 2" }, 
       new RoleViewModel { RoleId = 3, InRole = true, RoleName = "Role 3" } 
      } 
     }; 
     return View(model); 
    } 

    [HttpPut] 
    public ActionResult Update(UserRolesViewModel model) 
    { 
     // Here you will get the view model back containing the 
     // user id and the selected roles 
     // TODO: use AutoMapper to map back to a POCO and 
     // invoke the repository to update the database 
     return RedirectToAction("Edit"); 
    } 
} 
次いで

編集ビュー(~/Views/Roles/Edit.cshtml):

@model YourAppName.Models.UserRolesViewModel 
@{ 
    ViewBag.Title = "Edit user roles"; 
} 
<h2>Roles for user @Model.UserId</h2> 
@using (Html.BeginForm("Update", "Roles")) 
{ 
    @Html.HttpMethodOverride(HttpVerbs.Put) 
    @Html.HiddenFor(x => x.UserId) 
    @Html.EditorFor(x => x.Roles) 
    <input type="submit" value="update roles" /> 
} 

を最後に対応するエディタテンプレート(~/Views/Roles/EditorTemplates/RoleViewModel.cshtml):

@model YourAppName.Models.RoleViewModel 
<div> 
    @Model.RoleName 
    @Html.HiddenFor(x => x.RoleId) 
    @Html.CheckBoxFor(x => x.InRole) 
</div> 
+0

あなたはこの文の詳細はalittleがもらえ: 'その後、AutoMapperはUserRolesViewModel' –

+0

にモデルPOCOSをマッピングするために、私はautomapperに関する新しい質問をした:http://stackoverflow.com/questions/4653163/automapper -使用法 –

関連する問題