views:

104

answers:

2

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...

  1. 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.
  2. 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...

  1. Turn off the validation for the Position class when used in Player.
  2. 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.

+2  A: 

Not only to this particular problem, but in general, I would create a separate ViewModel instead of letting the view have the domain model. So, in your case, you don't need to overexpose your domain model (and getting things that you don't needed) to the view, and, nevertheless, turning off validation is most probably the worst solution

xandy
So, basically I have to make DTOs for all my views. Seems pretty inefficient to me. Does anyone else have a solution?
DFX
A: 

Create a custom ModelBinder that can validate this particular case for you.

xeb
Xeb, I'm having trouble finding good information on custom ModelBinders, think you could point me in the right direct?
DFX