0

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.

snowflakes74
  • 1,307
  • 1
  • 20
  • 43
  • Your not returning your model to the view, so `Model.ApplicationRoles.Count()` throws an exception because `ApplicationRoles` is `null`. It needs to be `return View(user);` in your `Create()` method –  Jul 20 '15 at 04:14
  • And once you correct that, it will still not work because you have `@Html.HiddenFor(model => model.ApplicationRoles[i].RoleId)` before `@Html.CheckBoxFor(model => model.ApplicationRoles[i].RoleId)` which means that in the POST method, you will only get back the initial value of `RoleId` - the value of the checkboxes will be ignored. –  Jul 20 '15 at 04:16

1 Answers1

0

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();
teo van kot
  • 12,350
  • 10
  • 38
  • 70