ASP.NET MVC Complex View Mapping

血红的双手。 提交于 2019-12-07 00:36:30

I would suggest 2 view models for editing

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 method

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);
}

View

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

EditorTemplate (RoleVM.cshtml)

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

POST method

[HttpPost]
public ActionResult Edit(UserVM model)
{
  // model.Roles now contains the ID of all roles and a value indicating if its been selected
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!