Search code examples
c#asp.net-mvcasp.net-mvc-4asp.net-identityrole-manager

Get the list of Roles in ASP.NET MVC


I have following methods to get the list of roles stored in AspNetRoles

    [AllowAnonymous]
    public async Task<ActionResult> Register()
    {
        //Get the list of Roles
        ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");

        return View();
    }

then I get it in view as follows

    <div class="form-group">
        <label class="col-md-2 control-label">
            Select User Role
        </label>
        <div class="col-md-10">
            @foreach (var item in (SelectList)ViewBag.RoleId)
            {
                <input type="checkbox" name="SelectedRoles" value="@item.Value" class="checkbox-inline" />
                @Html.Label(item.Value, new { @class = "control-label" })
            }
        </div>
    </div>

but once I load the page I'm getting Object reference not set to an instance of an object. error

Line 175: ViewBag.RoleId = new SelectList(await RoleManager.Roles.ToListAsync(), "Name", "Name");

This is RoleManager Definition

    public ApplicationRoleManager RoleManager
    {
        get
        {
            return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
        }
        private set
        {
            _roleManager = value;
        }
    }

this is ApplicationRoleManager Model

// Configure the RoleManager used in the application. RoleManager is defined in the ASP.NET Identity core assembly
public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
        : base(roleStore)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
    }
}

Solution

  • In Startup.Auth, reference the RoleManager like this:

        public void ConfigureAuth(IAppBuilder app)
        {
            // Add this reference
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        }
    

    Make sure your Controller includes this constructor:

            // Include this
            private ApplicationRoleManager _roleManager;
            // You already have this
            public ApplicationRoleManager RoleManager { get { return _roleManager ?? HttpContext.GetOwinContext().Get<ApplicationRoleManager>(); } private set { _roleManager = value; } }
    

    Rebuild, try again and hopefully this will sort it out.