更新时间:2023-02-25 19:10:34
最简单的方法是创建一个自定义的视图模型,其中包含用户本身和角色他是成员。实现可能如下所示:
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>