Reputation: 1362
I am working on an admin page where someone can go in and make some changes in the database. I want them to be able to view all non-admin users and edit them as well. After digging around online, I have figured out how to list out the users by email address and I have a Roles column. But the value showing up under Roles is not quite correct. It is the UserID in the AspNetUserRoles table. Here is my AdminController code that is grabbing the users and roles:
using (var db = new ApplicationDbContext())
{
model.AppUsers = db.Users
.Include("Roles")
.Select(u =>
new ManagerUserViewModel
{
UserID = u.Id,
UserName = u.UserName,
Email = u.Email,
Roles = u.Roles.ToList()
}
).ToList();
};
return View(model);
And here is my ManagerUserViewModel:
public class ManagerUserViewModel
{
public String UserID { get; set; }
public String Email { get; set; }
public String UserName { get; set; }
public IEnumerable<IdentityUserRole> Roles { get; set; }
}
Let me know if any other code is needed.
Here is what I am getting output on the page now:
Upvotes: 1
Views: 1627
Reputation: 563
Can you access the UserManager instance? If so it has a GetRoles function which takes a userId and returns a List of roles.
using (var db = new ApplicationDbContext())
{
model.AppUsers = db.Users
.Include("Roles")
.Select(u =>
new ManagerUserViewModel
{
UserID = u.Id,
UserName = u.UserName,
Email = u.Email
}
).ToList();
};
foreach(var user in model.AppUser){
user.Roles = userManager.GetRoles(user.UserId);
}
You'll need to update your viewmodel
public IEnumerable<String> Roles { get; set; }
If you don't have the UserManager you should be able to get it from the OwinContext
var userManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
Upvotes: 1