ASP.NET MVC复杂视图映射

本文关键字:视图 映射 复杂 MVC NET ASP | 更新日期: 2023-09-27 18:22:38

我环顾四周,找到了一些接近的答案,但我还没有看到这样的答案:

使用实体框架,我有以下内容:

榜样:

public class Role
{
    [Key]
    public short RoleId { get; set; }
    public string RoleName { get; set; }
    public string RoleDescription { get; set; }
}

A用户模型:

public class User
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }
    //more fields etc...
    public virtual ICollection<UserRole> UserRoles { get; set; }
}

和UserRole模型:

public class UserRole
{
    [Key]
    public int UserRoleId { get; set; }
    public int UserId { get; set; }
    public short RoleId { get; set; }
    public virtual Role Role { get; set; }
}

我想做的是确定如何组成视图模型,以便在创建新用户时显示所有可用角色的列表,在编辑用户时显示可用+选定角色的列表。我已经可以用前臂完成第一部分了,但我觉得它很脏。

在我看到的所有示例中,整个视图模型都封装在主视图上的IEnumerable中,并使用带有编辑器模板的@Html.EditorForModel()进行渲染。这似乎允许视图数据自动映射回底层模型。我想使用同样的技术来实现这一点,但我似乎无法在单一的用户模型中处理Role/UserRole的集合。

我引用的StackOverflow问题:动态生成复选框,并选择其中一些作为已检查

ASP.NET MVC复杂视图映射

我建议使用两个视图模型来编辑

public class RoleVM
{
  public short RoleId { get; set; }
  public string RoleName { get; set; }
  public bool IsSelected { get; set; }
}
public class UserVM
{
  public int Id { get; set; }
  public string Name { get; set; }
  public List<RoleVM> Roles { get; set; }
}

GET方法

public ActionResult Edit(int ID)
{
  UserVM model = new UserVM();
  // map all avaliable roles to model.Roles
  // map user to model, including setting the IsSelected property for the users current roles
  return View(model);
}

查看

@model YourAssembly.UserVM
...
@Html.TextBoxFor(m => m.Name)
...
@EditorFor(m => m.Roles)

编辑器模板(RoleVM.cs.html)

@model YourAssemby.RoleVM
@Html.HiddenFor(m => m.RoleId) // for binding
@Html.CheckBoxFor(m => m.IsSelected) // for binding
@Html.DisplayFor(m => Name)

POST方法

[HttpPost]
public ActionResult Edit(UserVM model)
{
  // model.Roles now contains the ID of all roles and a value indicating if its been selected