I’m having a moment. I can’t seem to get the selected items from a ListBox to be bound in a parameter to the action method that handles the post event.
Model is of type SystemRoleList:
public class SystemRoleList {
public IEnumerable<SystemRole> List { get; set; }
}
SystemRole is defined as:
public class SystemRole {
public Int32 Id { get; set; }
public String Name { get; set; }
}
This code generates the ListBox:
<%: this.Html.ListBox("Roles", new SelectList(Model.List, "Id", "Name")) %>
The action method receiving the selected items is set up like this:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateSystemRoles(Int32[] roles) {
// do something with the results....
}
The trouble is that roles is always null. I’ve tried using other data types – string[], ICollection<int>, and so on. I can see the values in the Request.Form collection if I do Request.Form["Roles[]"]. Typical values might be 1,3,4 if I selected those items from the ListBox.
How can I name either the ListBox or my parameter so that MVC will automatically bind the values?
Weird, the following works perfectly fine for me.
Model:
Controller:
View:
This being said I would use the strongly typed version of the
ListBoxhelper, like this:Model:
Controller:
View: