If I have a complex type e.g.
public class Customer
{
public int Id {get;set;}
public List<ContactType> ContactTypes {get;set;}
}
public class ContactType
{
public int Id {get;set;}
public string Name {get;set;}
}
and my strongly typed view binds the ContactType
like so ...
@Html.ListBoxFor(m => m.ContactTypes ,
new MultiSelectList(ViewBag.ContactTypes, "Id", "Name"))
and my action method signature is ...
public ActionResult Create(Customer customer){}
why is the customer.ContactTypes
null when I post the form? I c开发者_高级运维an see the posted data
like ContactTypes=1&ContactTypes=2
, I though this would bind to the ContactTypes
?
Can anyone point me in the right direction?
Your model is wrong. You should have a collection property to bind the selected values to. You should not use the same property for the both arguments of your SelectList. So start by adding a property on your view model to hold the selected ids:
public class Customer
{
public int Id { get; set; }
public List<int> SelectedContactTypeIds { get; set; }
public List<ContactType> ContactTypes { get; set; }
}
and then fix your view:
@Html.ListBoxFor(
m => m.SelectedContactTypeIds,
new MultiSelectList(Model.ContactTypes, "Id", "Name")
)
Now inside your Create
action you will get the SelectedContactTypeIds
property containing the selected ids:
public ActionResult Create(Customer customer)
{
// here the customer.SelectedContactTypeIds will contain the ids of the selected items
...
}
The reason why your code doesn't work is because you have bound the SelectList to the ContactTypes
property which is a complex type and as you know the <select>
element sends only the selected values when the form is submitted. That's how HTML works.
精彩评论