问题描述
我已经环顾四周,找到了一些接近的答案,但我还没有看到这样的一个:
I have looked around and found some close answers, but I haven't seen one yet like this:
使用实体框架我有以下内容:
Using Entity Framework I have the following:
角色模型:
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模型:
and a UserRole model:
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; }
}
我要做的是确定如何撰写一个viewmodel,创建新用户时可以显示所有可用角色的列表,以及编辑用户时可用的+所选角色列表。我可以实现已经使用foreach的第一部分,但是我觉得它很脏。
What I am trying to do is determine how to compose a viewmodel such that I can display a list of all available roles when creating a new user and a list of available+selected roles when editing a user. I can achieve the first part already using a foreach, but I feel like its dirty.
在我看到的所有示例中,整个viewmodel都包含在一个IEnumerable在主视图下,使用@ Html.EditorForModel()与编辑器模板进行呈现。这似乎允许视图数据的自动映射回到底层模型。我想使用相同的技术来实现这一点,但是我似乎并不关心在单一的用户模型中处理Role / UserRole的集合。
In all of the examples I have seen, the entire viewmodel is wrapped in an IEnumerable on main view and is rendered using @Html.EditorForModel() with an editor template. This seems to allow for automagic mapping of the view data back into the underlying model. I would like to achieve this using the same technique, but I can't seem to wrap my head around handling the collection of Role/UserRole within a singular User model.
StackOverflow问题我在引用:
StackOverflow question I am referencing: Generate Dynamically Checkboxes, And Select Some of them as Checked
推荐答案
我建议2个视图模型进行编辑
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方法
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)
EditorTemplate(RoleVM.cshtml)
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方法
[HttpPost]
public ActionResult Edit(UserVM model)
{
// model.Roles now contains the ID of all roles and a value indicating if its been selected
这篇关于ASP.NET MVC复杂视图映射的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!