How to iterate Roles in IEnumerable

2019-07-22 04:59发布

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

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.

The View Model is @model IEnumerable<XXXX_My_App.Models.ApplicationUser>. ApplicationUser has a base class of IdentityUser.

2条回答
看我几分像从前
2楼-- · 2019-07-22 05:06

If your Usermanager is returning a list of identityusers and so each identityuser should have a roles property which you should be able to enumerate. However this will only be populated if your implementation includes a class which implements IRoleStore but you haven't provided details of your implementation so we can only guess.

http://msdn.microsoft.com/en-us/library/dn613256(v=vs.108).aspx

查看更多
疯言疯语
3楼-- · 2019-07-22 05:23

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:

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

With that you can use the following model in your view to iterate over the appropriate properties

@model ICollection<YourProject.Models.UserRoleViewModel>
查看更多
登录 后发表回答