tags:

views:

49

answers:

2

where should the ViewModel creation take place? In the service layer, in the controller?

public class ObjectA {
 public string Name {get;set;}
 public IList<ChildB> Children {get;set;}
}

public class ObjectAViewModel {
 public ObjectA ObjectA {get;set;}
 public IList<ChildB> SelectableChildren {get;set;}
}

what if some properties on ObjectA have to be calculated at runtime?

public class ObjectA {
 public string Name {get;set;}
 public IList<ChildB> Children {get;set;}
 public CalculateMethod {get;set;}
 public decimal CalculatedValue {get;set;}
}

lets say that ObjectA.CalculatedValue is calculated out of all or some of the ChildB objects in the repository (not only the related objects), and that they are calculated differently depending on the CalculateMethod value? Should i extend the ObjectA, and in that case, where should i put it? together with ObjectA or, as a DTO somewhere else? And where should the calculation take place?

A: 

For you first question, i would say in the controller as it is it who knows which view it will serves, so what this view need to know.

Gregoire
+1  A: 

This seems to be a non-trivial question. There's a starting point for thought here and from there references to other discussions.

I'm from a Java background and so don't have direct experience of your world, but at a conceptual level my thinking goes:

Models don't know anything about views, they just make data available and can also make available validation rules that views may find helpful. For example: here's some date, this field is the "Department" field. Here is a list of all the valid departments, as a Model I know nothing a bout you Mr View but guess you might populate a drop-down list from that list of departments.

The problem with that is that the Model can end up sending huge amounts of data that the view doesn't care about, read on ...

Controllers don't know anything about the actual contents of views and models, but they do know that certain views are interested in certain models. So they have a responsibility to select an approariate View and arrange for it to get the data it needs. The Controller is rather like a dating agency, making introductions but then stepping away.

Hence in the most general scenario then View itself is given a Model and helps itself to the data it needs. So the View knows about the Model, but not vice-versa. Now as an implmentation detail we might pull out of that relationship a ViewModel class, to hold the interesting data for the view and we might also pull out the logic to a ViewModelFactory class. The controller may actually have responsibility for selecting the appropriate ViewModelFactory on the basis of the View we are going to, and hence in some sense the Controller is "making" the ViewModel, but the logic is the (conceptual) View's responsibility.

djna