Load list of roles for each user in MVC5 razor

2019-08-09 05:54发布

问题:

I am trying to display a row of each user and their roles in the ASP.net MVC application.

Users and their roles are stored in ASP.net membership provider table. Using the code below I can display each user and the role they are assigned, but my problem is if the user is in multiple roles then the user gets repeated.

I tried making UserRole as List but I am now stuck as I do not know how to add the roles to a list in the code below. Could you please provide me some direction?

My viewmodel is :

public class UserViewModel
{
   public string UserName { get; set; }
   public List<String> UserRole { get; set; }
}


var roles = ApplicationRoles.RolesList;
       var users = new List<UserViewModel>();
       foreach (var role in roles)
        {
           foreach (var user in Roles.GetUsersInRole(role)) 
            {
               users.Add(new UserViewModel {UserName = user, UserRole = role });
            }
        }

return View(users);

How can I load the roles so I do not repeat username if the user has multiple roles attached to him/her?

I would like to display it in the following format:

=======================

User | Role

John | Admin, Approver

Sam | Approver

=======================

回答1:

why dont you do like this

  foreach (var user in Roles.GetUsersInRole(role)) 
  {
      users.Add(new UserViewModel {UserName = user, NameAndRole = user + "|"+ String.Join(",", UserRole.ToArray() });
  }

or you can add property in your viewmodel class and use it

Public String NameAndRole
{
  get
   { return name + " | "+ String.Join(",", UserRole.ToArray()) }
}

MSDN : String.Join



回答2:

Do it the other way round: don't get users with a certain role, get the list of users and loop through that, using the Roles.GetRolesForUser method to get their list of rows.

var userList = Membership.GetAllUsers();

foreach(MembershipUser user in userList)
{
    string[] rolesArray = Roles.GetRolesForUser(user.UserName); 
    users.Add(new UserViewModel {UserName = user.UserName, UserRole = string.Join(",", rolesArray) });
}