tags:

views:

73

answers:

3

I'd like to see the SO's community response to this. I understand that a ViewModel is basically used to bind the view with data. When a form submits, should the object that be returned (modelbinded) be a ViewModel or an entity? I know a ViewModel IS an entity but I'm talking theoretically here. I want to make sure that myself and my team understand the concepts.

A: 

I use the ViewModel to pass data into the page and to get data out. All my forms to into a ViewModel first, which I'll run any validation I need on, and then I'll convert that to the appropriate DTO/Entity.

Parrots
But why do the conversion if your model binder can bind to appropriate DTO and apply the validation? Just wondering...
RailRhoad
@RailRhoad- think about things like "I agree to the terms and conditions".
RichardOD
@RichardOD- sorry Rich, I don't really know what you mean by that!
RailRhoad
@RichardOD - ok, I think it's about not extending discussion. Understood.
RailRhoad
Basically I was saying that there isn't always a straight mapping from a ViewModel to a DTO.
RichardOD
+2  A: 

I prefer to give a ViewModel to the view and have the ModelBinder bind to one of my business entities.

My ViewModels often contain little bits of display based data (e.g. whether or not to display widget A) so they don't really need to be bound.

Kindness,

Dan

Daniel Elliott
That's pretty much what I do but I notice quite a number of people binding to their view models.
RailRhoad
A: 

It's OK to do both as long as you don't compromise the design for the lazyness. E.g. it's not easy to bind to complex entities - one example is if entity does not have parameterless constructor - and if you avoid such entities just to make binding easy... it's bad. It's like making all variables "string" just because your UI control can't understand dates or floats. It may also lead to dumb DTO-like entites and anemic domain model. If, however, you don't need smart entities - it's OK to use them in model binding.

As always, it takes experience and good taste to make a decision. There's no simple rule. One way to avoid UI influence on domain design is to develop domain level first (TDD is a good help here). Another way is to have several "clients" for your domain layer - different requirements will make you extract the core functionality into the domain layer, moving specific things (like presentation attributes and formatting) to appropriate layers / view models.

queen3