Model Binding with Parent/Child Relationship
Posted
by user296297
on Stack Overflow
See other posts from Stack Overflow
or by user296297
Published on 2010-03-27T06:18:08Z
Indexed on
2010/03/27
6:23 UTC
Read the original article
Hit count: 235
I'm sure this has been answered before, but I've spent the last three hours looking for an acceptable solution and have been unable to find anything, so I apologize for what I'm sure is a repeat.
I have two domain objects, Player and Position. Player's have a Position. My domain objects are POCOs tied to my database with NHibernate. I have an Add action that takes a Player, so I'm using the built in model binding. On my view I have a drop down list that lets a user select the Position for the Player. The value of the drop down list is the Id of the position. Everything gets populated correctly except that my Position object fails validation (ModelState.IsValid) because at the point of model binding it only has an Id and none of it's other required attributes.
What is the preferred solution for solving this with ASP.NET MVC 2?
Solutions I've tried...
- Fetch the Position from the database based on the Id before ModelState.IsValid is called in the Add action of my controller. I can't get the model to run the validation again, so ModelState.IsValid always returns false.
- Create a custom ModelBinder that inherits from the default binder and fetch the Position from the database after the base binder is called. The ModelBinder seems to be doing the validation so if I use anything from the default binder I'm hosed. Which means I have to completely roll my own binder and grab every value from the form...this seems really wrong and inefficient for such a common use-case.
Solutions I think might work, I just can't figure out how to do...
- Turn off the validation for the Position class when used in Player.
- Write a custom ModelBinder leverages the default binder for most of the property binding, but lets me get the Position from the database BEFORE the default binder runs validation.
So, how do the rest of you solve this?
Thanks,
Dan
P.S. In my opinion having a PositionId on Player just for this case is not a good solution. There has to be solvable in a more elegant fashion.
© Stack Overflow or respective owner