Search code examples
asp.net-mvcasp.net-identityasp.net-roles

List of Users with roles in MVC Asp.net identity


I want to have list of all the users registered on my site with their roles.

Id | Name | Role


1 | ABC | Admin


2 | DEF | User

Something like this, I have made Roles controller in which all the roles is listed.

 public ActionResult Index()
    {
        var roles = context.Roles.ToList();
        return View(roles);
    }

In View

@model IEnumerable<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>
@{
    ViewBag.Title = "Index";
}    
<div>
    @foreach (var role in Model)
    {
        <p>
            <strong>@role.Name | </strong>
        </p>
    }
</div>

This will list all the roles but i want user's list with their roles.

Please give any solution, Thanks


Solution

  • Create a new class called UserViewModel. This will act as a view model for your page.

    public class GroupedUserViewModel
    {
        public List<UserViewModel> Users {get; set;}
        public List<UserViewModel> Admins {get; set;}
    }
    
    public class UserViewModel
    {
        public string Username {get; set;}
        public string Roles {get; set;}
    }
    

    In the controller's action method, get the list of users along with their roles and map that to the UserViewModel.

    public ActionResult Index()
    {
        var allusers = context.Users.ToList();
        var users = allusers.Where(x=>x.Roles.Select(role => role.Name).Contains("User")).ToList();
        var userVM = users.Select(user=>new UserViewModel{Username = user.FullName, Roles = string.Join(",", user.Roles.Select(role=>role.Name))}).ToList();
    
        var admins = allusers.Where(x=>x.Roles.Select(role => role.Name).Contains("Admin")).ToList();
        var adminsVM = admins.Select(user=>new UserViewModel{Username = user.FullName, Roles = string.Join(",", user.Roles.Select(role=>role.Name))}).ToList(); 
        var model = new GroupedUserViewModel{Users = userVM, Admins = adminsVM};
    
        return View(model);
    }
    

    Then use the new model in the view. Make sure to use correct namespace here where you defined your view model.

    @model Models.GroupedUserViewModel
    @{
        ViewBag.Title = "Index";
    }    
    <div>
        @foreach (var user in Model.Admins)
        {
            <p>
                <strong>@user.Username | @user.Roles </strong>
            </p>
        }
    
        @foreach (var user in Model.Users)
        {
            <p>
                <strong>@user.Username | @user.Roles </strong>
            </p>
        }
    </div>