c# - Get the list of Roles in ASP.NET MVC -


i have following methods list of roles stored in aspnetroles

    [allowanonymous]     public async task<actionresult> register()     {         //get list of roles         viewbag.roleid = new selectlist(await rolemanager.roles.tolistasync(), "name", "name");          return view();     } 

then in view 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 load page i'm getting object reference not set instance of object. error

line 175: viewbag.roleid = new selectlist(await rolemanager.roles.tolistasync(), "name", "name");

this rolemanager definition

    public applicationrolemanager rolemanager     {                 {             return _rolemanager ?? httpcontext.getowincontext().get<applicationrolemanager>();         }         private set         {             _rolemanager = value;         }     } 

this applicationrolemanager model

// configure rolemanager used in application. rolemanager defined in 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>()));     } } 

in startup.auth, reference rolemanager this:

    public void configureauth(iappbuilder app)     {         // add reference         app.createperowincontext<applicationrolemanager>(applicationrolemanager.create);     } 

make sure controller includes constructor:

        // include         private applicationrolemanager _rolemanager;         // have         public applicationrolemanager rolemanager { { return _rolemanager ?? httpcontext.getowincontext().get<applicationrolemanager>(); } private set { _rolemanager = value; } } 

rebuild, try again , sort out.


Comments

Popular posts from this blog

java - Run spring boot application error: Cannot instantiate interface org.springframework.context.ApplicationListener -

reactjs - React router and this.props.children - how to pass state to this.props.children -

Excel VBA "Microsoft Windows Common Controls 6.0 (SP6)" Location Changes -