1

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

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

snowflakes74
  • 1,307
  • 1
  • 20
  • 43
  • Did you get this to work how you wanted? I used the selected answer, but my roles are blank, and I know I have users with roles. – RoLYroLLs Dec 02 '15 at 19:50

2 Answers2

1

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) });
}
user1666620
  • 4,800
  • 18
  • 27
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

Pranay Rana
  • 175,020
  • 35
  • 237
  • 263