Download role list for each user in MVC5 razor

I am trying to show each user's string and their roles in an ASP.net MVC application.

Users and their roles are stored in the ASP.net membership provider table. Using the code below, I can display each user and the role that they have assigned, but my problem is that the user is in several roles, after which the user repeats.

I tried to make UserRole as a List, but now I'm stuck since I don’t know how to add roles to the list in the code below. Could you give me some direction?

My view model:

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 roles so as not to repeat the username if the user has several roles associated with it?

I would like to display it in the following format:

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

|

| Admin, Approver

|

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

+1
2

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

viewmodel

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

MSDN: String.Join

+1

: , , Roles.GetRolesForUser, .

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) });
}
+1

Source: https://habr.com/ru/post/1618332/


All Articles