Search code examples
c#asp.netasp.net-mvcuser-roles

Get all users and their roles they got into a table asp.net mvc


Im trying to figure out how to get all users and their Roles into a nice organized table, seen many different ways to go, but none has worked for me. i have gotten abit on the way atleast... anyone that can help me out?

With this code i get all the roles:

        var context = new ApplicationDbContext();
        var roleStore = new RoleStore<IdentityRole>(context);
        var roleManager = new RoleManager<IdentityRole>(roleStore);
        var roles = (from r in roleManager.Roles select r.Name).ToList();
        ViewBag.Roles = roles.ToList();

and with this code i get all the registered users:

        var context = new ApplicationDbContext();
        var userStore = new UserStore<ApplicationUser>(context);
        var userManager = new UserManager<ApplicationUser>(userStore);
        var users = (from u in userManager.Users select u.UserName).ToList();
        ViewBag.Users = users.ToList();

and finally with this code i get all the users id's

        var context = new ApplicationDbContext();
        var user = (from u in userManager.Users select u.Id).ToList();
        ViewBag.id = user.ToList();

But how do i get All the users with their roles? i really cant figure it out


Solution

  • Here's one option to get a list of users (with username) and list of associated roles.

    Controller:

    public ActionResult GetRoles()
            {
                var userRoles = new List<RolesViewModel>();
                var context = new ApplicationDbContext();
                var userStore = new UserStore<ApplicationUser>(context);
                var userManager = new UserManager<ApplicationUser>(userStore);
    
                //Get all the usernames
                foreach (var user in userStore.Users)
                {
                    var r = new RolesViewModel
                    {
                        UserName = user.UserName
                    };
                    userRoles.Add(r);
                }
                //Get all the Roles for our users
                foreach (var user in userRoles)
                {
                    user.RoleNames = userManager.GetRoles(userStore.Users.First(s=>s.UserName==user.UserName).Id);
                }
    
                return View(userRoles);
            }
    

    ViewModel

    public class RolesViewModel
    {
        public IEnumerable<string> RoleNames { get; set; }
        public string UserName { get; set; }
    }
    

    View: Simple one

    @model IEnumerable<StackOverflow.Models.RolesViewModel>
    @foreach (var user in Model.ToList())
    {
        <div> @user.UserName -- </div>
        foreach (var role in user.RoleNames)
        {
            <div> @role </div>
        }
        <br />
    }