Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 569
per källström Avatar asked Dec 10 '25 00:12

per källström


1 Answers

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 />
}
like image 129
IndieTech Solutions Avatar answered Dec 12 '25 12:12

IndieTech Solutions



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!