How to iterate Roles in IEnumerable<ApplicationUser> and display role names in razor view
asp.net-identity, asp.net-mvc, c#
Solution
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>
Problem
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.