返回一个集合对象,同时这个集合的对象的属性又是一个集合对象的处理方法(ViewModel)

如果遇到需要返回一个集合对象,其中该集合中的属性又是一个集合。第一种:可在考虑用外键关联,比如在控制器中可以采用预先加载的方式加载关联的数据,比如 RoleManager.Roles.Include<x =>r.Users>.ToList();

第二种 可以考虑使用视图模型ViewModel的方式。第二种方式的适用范围更加广泛,第一种方式使用较为简单,但使用的场合有限。

一、建立视图模型 ViewModel

public class IndexRoleViewModel
{
public string Id { get; set; }

[Required(AllowEmptyStrings = false)]
[Display(Name = "角色名称")]
public string Name { get; set; }

[Display(Name = "角色描述")]
[StringLength(50, ErrorMessage = "{0}不能超过50个字符")]
[DataType(DataType.MultilineText)]
public string Description { get; set; }

public List<ApplicationUser> ApplicationUsers { get; set; }   //属性为一个集合。就定义一个List泛型对象。

}

二、控制器:

public async Task<ActionResult> Index()   //这里采用了异步方法,要使用异步方法,必须引入/ System.Data.Entity命名空间。
{
var rolesList =new List<IndexRoleViewModel>();
foreach (var role in await RoleManager.Roles.ToListAsync())
{
var _IndexRoleViewModel = new IndexRoleViewModel()
{
Id = role.Id,
Name = role.Name,
Description = role.Description,
ApplicationUsers =new List<ApplicationUser>() //特别注意,初始化一个空的List泛型集合。如果不初始化,将为触发一个引用为Null的异常。
};

foreach (var user in await UserManager.Users.ToListAsync()) //遍历用户
{
if (UserManager.IsInRole(user.Id,role.Name))  //如果用户拥有这个角色,就加入到viewModel 对象的List属性中。
{
_IndexRoleViewModel.ApplicationUsers.Add(user);
}
}

rolesList.Add(_IndexRoleViewModel);
}



return View(rolesList.ToList()); //异步方法在 System.Data.Entity命名空间下面。
}

三、视图:

@model IEnumerable<MajorConstruction.Areas.Admin.Models.IndexRoleViewModel>  //模型为IEnumerabel<ViewModel> 类型。

@{
ViewBag.Title = "角色列表";
}
<h2>@ViewBag.Title</h2>
<hr />
<p>
@Html.ActionLink("新建角色", "Create")
</p>
<table class="table table-striped table-hover">
<thead>
<tr>
<th>
@Html.DisplayName("角色名称")
</th>
<th>
@Html.DisplayNameFor(model => model.Description)
</th>
<th>@Html.DisplayName("拥有此角色的成员")</th>
<th></th>
</tr>
</thead>
<tbody>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Description)
</td>
<td>
<ol>  //使用有序列表在表格中来显示属性的多字段。
@foreach (var userForRole in item.ApplicationUsers)  
{
<li>@userForRole.UserName | @userForRole.RealName</li>
}
</ol>
</td>
<td>
@Html.ActionLink("编辑", "Edit", new { id = item.Id }) |
@Html.ActionLink("详细", "Details", new { id = item.Id }) |
@Html.ActionLink("删除", "Delete", new { id = item.Id })
</td>
</tr>
}
</tbody>
</table>

原文地址:https://www.cnblogs.com/liuyuanhao/p/4528274.html