c# - Create a checkboxlist of user roles MVC5 razor -


this question has answer here:

i trying show checkbox list of application roles in view.

i not sure how populate view roles pull aspnet_roles table.

if use code below null reference exception because applicationroles empty.

could please me or guide me of best way achieve this?

viewmodel code

 public class userviewmodel  {     public string username { get; set; }     public list<aspnet_roles> applicationroles { get; set; }  } 

and in controller trying load them using following code

 public actionresult create()  {     userviewmodel user = new userviewmodel();     user.applicationroles = db.aspnet_roles.tolist();      viewbag.applicationroles = new selectlist(db.aspnet_roles.tolist(),"roleid","rolename");         return view();  } 

in view

@using test.web.models; @model test.web.models.userviewmodel  @using (html.beginform("create", "users", formmethod.post)) { @html.validationsummary(true)   <div>     <div>         @html.labelfor(model => model.userrole})         <div>             @for (var = 0; < model.applicationroles.count(); i++)             {                     var role = model.applicationroles[i];                     @html.hiddenfor(model => model.applicationroles[i].roleid)                     @html.checkboxfor(model => model.applicationroles[i].roleid)                     @html.labelfor(model => model.applicationroles[i].rolename)             }         </div>      </div>   </div> } 

thank in advance.

i gess problem in line:

@for (var = 0; < userviewmodel.applicationroles.count(); i++) 

it should be

@for (var = 0; < model.applicationroles.count(); i++) 

and in controller should pass viewmodel view:

viewdata.model = user; return view(); 

Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -