ASP.NET MVC model binding foreign key relationship
- by Rory Fitzpatrick
Is it possible to bind a foreign key relationship on my model to a form input?
Say I have a one-to-many relationship between Car and Manufacturer. I want to have a form for updating Car that includes a select input for setting Manufacturer. I was hoping to be able to do this using the built-in model binding, but I'm starting to think I'll have to do it myself.
My action method signature looks like this:
public JsonResult Save(int id, [Bind(Include="Name, Description, Manufacturer")]Car car)
The form posts the values Name, Description and Manufacturer, where Manufacturer is a primary key of type int. Name and Description get set properly, but not Manufacturer, which makes sense since the model binder has no idea what the PK field is. Does that mean I would have to write a custom IModelBinder that it aware of this? I'm not sure how that would work since my data access repositories are loaded through an IoC container on each Controller constructor.