如何在迭代的IEnumerable<角色; ApplicationUser>在剃刀视图显示角色名称 [英] How to iterate Roles in IEnumerable<ApplicationUser> and display role names in razor view
问题描述
PM。我的一个观点得到所有用户的列表与此GET控制器操作:
Am using Identity 2.1.0 with MVC and razor Views. One of my views gets a list of all users with this GET Controller Action:
public async Task<ActionResult> Users()
{
return View(await UserManager.Users.ToListAsync());
}
在查看有一个foreach,通过每个用户进行迭代,并显示通常的要知道像电子邮件地址,用户名等信息,我想如果有也是通过每个用户的角色迭代,这样我可以显示每个用户像这样的角色成员资格的方式:
Within the View there is a foreach that iterates through each user and displays the usual information like email address, username, etc. I would like to know if there is also a way of iterating through the roles for each user so that I can display the role membership of each user something like this:
Customer
Employee
我一直没能想出解决办法。我的问题的部分原因是,我没有任何智能感知剃刀视图中,并一直无法找到任何关于谷歌的帮助。
I haven't been able to figure this out. Part of my problem is that I don't have any Intellisense within razor views and haven't been able to find anything helpful on Google.
视图模型是 @model IEnumerable的< XXXX_My_App.Models.ApplicationUser>
。 ApplicationUser有一个基类IdentityUser的。
The View Model is @model IEnumerable<XXXX_My_App.Models.ApplicationUser>
. ApplicationUser has a base class of IdentityUser.
推荐答案
最简单的方法是创建一个自定义的视图模型,其中包含用户本身和角色他是成员。实现可能如下所示:
The easiest way would be to create a custom ViewModel which contains the user itself and the roles he is member of. An implementation could look like the following:
控制器
public async Task<ViewResult> Users()
{
var users = UserManager.Users;
var model = new Collection<UserRoleViewModel>();
foreach (var user in users)
{
var roles = await UserManager.GetRolesAsync(user.Id);
var rolesCollection = new Collection<IdentityRole>();
foreach (var role in roles)
{
var role = await RoleManager.FindByNameAsync(roleName);
rolesCollection.Add(role);
}
model.Add(new UserRoleViewModel { User = user, Roles = rolesCollection });
}
return View("Users", model);
}
UserRoleViewModel
public class UserRoleViewModel
{
public ApplicationUser User { get; set; }
public Collection<IdentityRole> Roles { get; set; }
}
使用,你可以用下面的模型在视图中遍历相应的属性。
With that you can use the following model in your view to iterate over the appropriate properties
@model ICollection<YourProject.Models.UserRoleViewModel>
这篇关于如何在迭代的IEnumerable<角色; ApplicationUser>在剃刀视图显示角色名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!