Create a checkboxlist of user roles MVC5 razor

949 Views Asked by At

I am trying to show a checkbox list of application roles in a view.

I am not sure how to populate view with all the roles that I pull from the aspnet_roles table.

If I use the code below I get null reference exception because ApplicationRoles is empty.

Could anyone please help me or guide me of what is the best way to achieve this?

ViewModel code is

 public class UserViewModel
 {
    public string UserName { get; set; }
    public List<aspnet_Roles> ApplicationRoles { get; set; }
 }

and in controller I am trying to load them by 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 this is

@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 i = 0; i < 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 you in advance.

1

There are 1 best solutions below

1
teo van kot On

I gess your problem in this line:

@for (var i = 0; i < UserViewModel.ApplicationRoles.Count(); i++)

it should be

@for (var i = 0; i < Model.ApplicationRoles.Count(); i++)

And in your Controller you should pass your ViewModel to View:

ViewData.Model = user;
return View();