ASP.NET MVC model binding foreign key relationship
Posted
by Rory Fitzpatrick
on Stack Overflow
See other posts from Stack Overflow
or by Rory Fitzpatrick
Published on 2009-03-19T15:29:22Z
Indexed on
2010/04/08
5:43 UTC
Read the original article
Hit count: 902
asp.net-mvc
|model-binding
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.
© Stack Overflow or respective owner