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 ?

Amit Philips
  • 387
  • 6
  • 17
  • You could use https://github.com/thinktecture/Thinktecture.IdentityManager which is created for managing asp.net identity framework users, roles and other operations. – DSR Sep 20 '14 at 22:52

2 Answers2

0

Does @Model.Roles in View strongly typed against @model WebApplicationName.Models.ApplicationUser does not work for you?

Controller:

public ActionResult NameOfTheView(){return View(db.Users.ToList());}
Yoda
  • 17,363
  • 67
  • 204
  • 344
  • But how does that allow me to display both name and role name of all the users ? Even User.IsInRole only allows for checking the role of a logged in user. – Amit Philips Sep 20 '14 at 14:48
  • @Yoda, yeah this alone doesn't work because `Users.Roles`, does not have the role's name. – RoLYroLLs Dec 02 '15 at 14:56
0

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.

Amit Philips
  • 387
  • 6
  • 17
  • This doesn't work for every scenario. I have users who are in more than one role, e.g: Staff, HR, Payroll. This solution spits out a user with these roles 3 times. The closest I've found is this: `var users = allUsers.Select(u => new UserViewModel {Id = u.Id, UserName = u.UserName, Email = u.Email, Roles = String.Join(",", u.Roles.Select(r => r.RoleId))}).ToList();` but how can i continue this lambda (or convert it to LINQ) to get the role names. – RoLYroLLs Dec 02 '15 at 15:01