Search code examples
asp.netasp.net-mvcasp.net-identity-2

List User and Role in asp.net identity 2.0


How do i display a list of Users and their Roles in ASP.NET Identity 2.0.

Example...

John Doe - Admin Bob Smith - User

So far I have created a UserRoleViewModel

public string fname { get; set; }
public string rname { get; set; }

In the controller, I have done the following...

ApplicationDbContext db = new ApplicationDbContext();

UserRoleViewModel obj = new UserRoleViewModel();

var result = from u in db.Users
             select new UserRoleViewModel
             {
                fname = u.FirstName,
                rname = ???
             };

return View(result);

Is this the correct approach ? If yes, how do i get the role for the user in rname ?


Solution

  • Finally got a solution for my problem...

    This is the ViewModel I created...

    public class UserRoleViewModel
    {
        public string fname { get; set; }
        public string rname { get; set; }
    }
    

    This is the Controller...

    public ActionResult Users()
    {
       var result = from user in db.Users
                    from role in db.Roles
                    where role.Users.Any(r => r.UserId == user.Id)
                    select new UserRoleViewModel
                    {
                        fname = user.FirstName,
                        rname = role.Name
                    };
    
            return View(result);
    }
    

    And this is the view...

    @model IEnumerable<ApplicationName.Models.UserRoleViewModel>
    <ul>
        @foreach(var u in Model)
        { 
           <li>@u.fname - @u.rname</li>
        }
    </ul>
    

    I'm still new to LINQ, Lambda and MVC in general. If someone has a way to better this code, please feel free to add in your views.