I’m trying to bind a ListBox in my partial view but I’m getting the exception…
Object reference not set to an instance of an object.
Referencing @Html.ListBoxFor(x => x.SelectedRoles, Model.Roles)
I’m not sure what I’m doing wrong…
Model:
public class RegisterModel {
public string UserName { get; set; }
public string Email { get; set; }
public string Password { get; set; }
public string ConfirmPassword { get; set; }
public string[] SelectedRoles { get; set; }
public MultiSelectList Roles { get; set; }
}
Controller:
public class AdminController : Controller {
[ChildActionOnly]
public ActionResult _AddUser() {
var model = new RegisterModel {
Roles = new MultiSelectList(Roles.GetAllRoles())
};
return View(model);
}
}
PartialView _AddUser.cshtml:
@model RobotDog.Models.RegisterModel
@using(Html.BeginForm("_AddUser","Admin", FormMethod.Post)) {
@Html.EditorFor(x => x.Email, new { @class = "input-xlarge", @placeholder = "Email"})
@Html.EditorFor(x => x.UserName, new { @class = "input-xlarge", @placeholder = "User Name"})
@Html.EditorFor(x => x.Password, new { @class = "input-xlarge", @placeholder = "Password"})
@Html.ListBoxFor(x => x.SelectedRoles, Model.Roles)
}
Here is the view that is referencing _AddUser.cshtml
Users.cshtml:
@model IEnumerable<RobotDog.Models.UserModel>
<table></table>
<div id="addUser">
@Html.Partial("_AddUser", new ViewDataDictionary())
</div>
The problem with your example is that by calling @Html.Partial you’re rendering the partial _AddUser without ever going through the controller _AddUser method. This means that the Model of the partial view has no Model.Roles to access. You can resolve this a couple of different ways.
One possibility is to use @Html.RenderAction or @Html.Action to call the controller method and let the controller method _AddUser populate the values as you’ve set it up to do.