3

I have implemented the Identity 2.0 membership and starting to regret it now. But, I'm so deep in this project there is no turning around. My issue is probably simple to most so hopefully I can get some assistance.

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's 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 display each registered user's role using the grid.Column just like email, employeeID, and phoneNumber.

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>();
}

Within my using statement, I have var roleManager and var userManager but they are not doing anything. I was trying to retrieve the user's role, but that's when I stopped and figured I would reach out to SOF for some tips or better approach.

Now, on a side note. There are some service methods already created in the project which work great within other controller methods. Maybe these can be used or modified in my issue 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.

JoshYates1980
  • 3,476
  • 2
  • 36
  • 57
  • read [this](http://stackoverflow.com/questions/6263927/role-management-in-mvc3) might be help – VeNoMiS Sep 03 '14 at 16:47
  • @VeNoMiS your linked question is from 2011. There was no Identity framework back then. – trailmax Sep 03 '14 at 22:25
  • 1
    By the way, Josh, your implementation of `IsCurrentUserInRole` is excessive. You can call `ClaimsPrincipal.Current.IsInRole("rolename")` and it will do just the same without any calls to the database. – trailmax Sep 03 '14 at 22:28
  • An update since this post, I recommend this for identity and role management: https://github.com/imranbaloch/ASPNETIdentityWithOnion – JoshYates1980 Feb 06 '17 at 21:44

1 Answers1

0

Use await UserManager.GetRolesAsync(user) to return list of strings with roles assigned. Because user can have many roles there is no such thing as "user role", there are roles. So if you'd like to show roles in the table, you'll need to join them into CSV. Something like this:

var roles = await UserManager.GetRoles.Async();
var allUserRoles = String.Join(", ", roles);
_PTSUsersViewModel._roles = allUserRoles;
trailmax
  • 34,305
  • 22
  • 140
  • 234