I’m trying to create a MultiSelectList in my view but an exception is being thrown on this line in the PartialView:
@Html.ListBoxFor(x => x.RegisterModel.SelectedRoles, Model.RegisterModel.Roles)
There is no ViewData item of type ‘IEnumerable’ that has the key ‘RegisterModel.SelectedRoles’.
I would like the MultiSelectList to be a list of all roles, but I’m not quite sure what I’m doing wrong. I originally made RegisterModel.SelectedRoles a string[] because when adding a user to roles a string[] is expected as an argument to System.Web.Security.Roles.AddUserToRoles().
Model
public class DynamicActionUserModel {
public string Action { get; set; }
public RegisterModel RegisterModel { get; set; }
}
public class RegisterModel {
public string[] SelectedRoles { get; set; }
public MultiSelectList Roles { get; set; }
}
Controller
[HttpGet]
public ActionResult CreateUser() {
DynamicActionUserModel model = new DynamicActionUserModel {
Action = "CreateUser",
RegisterModel = new RegisterModel {
Roles = new MultiSelectList(System.Web.Security.Roles.GetAllRoles().OrderBy(r => r))
}
};
return PartialView("_UserPartial", model);
}
View
<div>
@Html.Partial("_UserPartial", new DynamicActionUserModel{ Action = "CreateUser", RegisterModel = new RegisterModel()})
</div>
PartialView
@Html.LabelFor(x => x.RegisterModel.Roles)
@Html.ListBoxFor(x => x.RegisterModel.SelectedRoles, Model.RegisterModel.Roles)
On this line you are rendering the
_UserPartialpartial but the model you have passed to this view is empty, you simply instantiated it but there are no roles inside:The
CreateUseraction is never invoked to populate the Roles property.You probably want to invoke it as a child action:
Now the CreateUser action will be invoked as a child action, it will populate the Roles property of the model and pass it to the partial. The result of the execution of this partial will then be injected into the containing
<div>.Take a look at the following article to better understand the difference between
Html.PartialandHtml.Action.