2011-01-10 34 views
6

如何在視圖和控制器中處理多對多映射(在usersroles的上下文中)?asp.net mvc視圖和控制器中的多對多

我使用實體框架映射到純波蘇斯這樣的:

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

可不可以給小有一點該語句的更多信息:`然後AutoMapper到模型波蘇斯映射到UserRolesViewModel` – 2011-01-11 00:28:52