c# - 如何迭代 IEnumerable<ApplicationUser> 中的角色并在 razor View 中显示角色名称

标签 c# asp.net-mvc asp.net-identity

正在使用具有 MVC 和 razor View 的 Identity 2.1.0。我的一个 View 通过此 GET Controller 操作获取所有用户的列表:

public async Task<ActionResult> Users()
{
    return View(await UserManager.Users.ToListAsync());
}

在 View 中,有一个 foreach 迭代每个用户并显示常用信息,如电子邮件地址、用户名等。我想知道是否还有一种方法可以迭代每个用户的角色,以便我可以显示每个用户的角色成员身份,如下所示:

Customer
Employee

我一直没能弄清楚这一点。我的部分问题是我在 razor View 中没有任何 Intellisense,并且无法在 Google 上找到任何有用的信息。

View 模型是@model IEnumerable<XXXX_My_App.Models.ApplicationUser> 。 ApplicationUser 有一个 IdentityUser 基类。

最佳答案

最简单的方法是创建一个自定义 ViewModel,其中包含用户本身以及他所属的角色。实现可能如下所示:

Controller

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

这样,您就可以在 View 中使用以下模型来迭代适当的属性

@model ICollection<YourProject.Models.UserRoleViewModel>

关于c# - 如何迭代 IEnumerable<ApplicationUser> 中的角色并在 razor View 中显示角色名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588758/

相关文章:

c# - ASP.NET Identity 在登录时对每个页面请求执行数据库查询

c# - 创建 .net tcp 服务器

c# - WCF 之外的项目中的 DataContract

C#多线程单元测试

asp.net-mvc - 为什么在 Html Helper 中使用 ASP NET MVC 中的日期格式不同?

c# - 在 MVC View 中使用 switch case

c# - 如何保护 ASP.NET Web API 2

c# - 转换为值类型失败,因为物化值为 null

c# - 在 C# 中使用 LINQ 在范围之间分组数据

asp.net-mvc - 如何将身份成员资格与现有数据库(n 层)一起使用