MVC Identity 2.0 and Role Management
I have implemented Identity 2.0 Membership and now regret it. But, I'm so deep in this project, there is no turning point. My problem is probably simple for most, so hopefully I can get some help.
I have a grid control in my MVC5 application.
VIEW
@using System.Web.Helpers;
@model List<PTSPortal.Models.PTSUsersViewModel>
@{
var grid = new WebGrid(source: Model, defaultSort: "PropertyName", rowsPerPage: 10);
}
<div id="ContainerBox">
@grid.GetHtml(columns: grid.Columns(
grid.Column("_email", "Email", canSort: true, style: "text-align-center"),
grid.Column("_employeeID", "EmployeeID", canSort: true, style: "text-align-center"),
grid.Column("_phoneNumber", "Phone", canSort: true, style: "text-align-center")
//-----I want to display the user role here!------
))
</div>
ViewModel
public class PTSUsersViewModel
{
public string _ID { get; set; }
public string _email { get; set; }
public int? _employeeID { get; set; }
public string _phoneNumber { get; set; }
public string _role { get; set; }
}
My goal is to show every registered user role using grid.Column, like email, employeeID and phone number.
CONTROLLER
public ActionResult PTSUsers()
{
List<PTSUsersViewModel> viewModel = FetchInfo().ToList();
return View(viewModel);
}
private static IEnumerable<PTSUsersViewModel> FetchInfo()
{
PTSPortalEntities context = new PTSPortalEntities();
using (ApplicationDbContext _context = new ApplicationDbContext())
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
}
return (from a in context.AspNetUsers
orderby a.Email ascending
select new PTSUsersViewModel
{
_ID = a.Id,
_email = a.Email,
_employeeID = a.EmployeeID,
_phoneNumber = a.PhoneNumber,
//_role = ........
}).ToList<PTSUsersViewModel>();
}
In my usage instruction, I have var roleManager and var userManager, but they don't do anything. I was trying to get the user role, but when I stopped and thought I would turn to SOF for some advice or a better approach.
Now, on a side note. The project already has some maintenance methods that work great within other controller methods. Maybe they can be used or changed in my release above:
public class AppServices
{
// Roles used by this application
public const string AdminRole = "Admin";
public const string TrainerRole = "Trainer";
private static void AddRoles(ref bool DataWasAdded)
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
if (roleManager.RoleExists(AdminRole) == false)
{
Guid guid = Guid.NewGuid();
roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = AdminRole });
DataWasAdded = true;
}
if (roleManager.RoleExists(TrainerRole) == false)
{
Guid guid = Guid.NewGuid();
roleManager.Create(new IdentityRole() { Id = guid.ToString(), Name = TrainerRole });
DataWasAdded = true;
}
}
/// <summary>
/// Checks if a current user is in a specific role.
/// </summary>
/// <param name="role"></param>
/// <returns></returns>
public static bool IsCurrentUserInRole(string role)
{
if (role != null)
{
using (ApplicationDbContext _context = new ApplicationDbContext())
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
if (UserManager.IsInRole(GetCurrentUserID(), role))
{
return true;
}
}
}
return false;
}
/// <summary>
/// Adds a user to a role
/// </summary>
/// <param name="userId"></param>
/// <param name="RoleToPlaceThemIn"></param>
public static void AddUserToRole(string userId, string RoleToPlaceThemIn)
{
// Does it need to be added to the role?
if (RoleToPlaceThemIn != null)
{
using (ApplicationDbContext _context = new ApplicationDbContext())
{
var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(_context));
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(_context));
if (UserManager.IsInRole(userId, RoleToPlaceThemIn) == false)
{
UserManager.AddToRole(userId, RoleToPlaceThemIn);
}
}
}
}
Any advice would be appreciated.
source to share
Use await UserManager.GetRolesAsync(user)
to return a list of strings with assigned roles. Since a user can have many roles, there is no such thing as a "user role", there are roles . So if you want to show roles in a table, you need to join them in CSV. Something like that:
var roles = await UserManager.GetRoles.Async();
var allUserRoles = String.Join(", ", roles);
_PTSUsersViewModel._roles = allUserRoles;
source to share