views:

1006

answers:

2

And what do you put in your View?

A recent blog from Scott Hanselman about using a special model binder for easier testing led me to think about the following: What do you put in your controller logic building the view model, and what should be put in the view? what he does is this:

var viewModel = new DinnerFormViewModel {  
    Dinner = dinner,  
    Countries = new SelectList(PhoneValidator.Countries, dinner.Country)  
};  
return View(viewModel);

Now, I use the same way of passing data to my view, but I am unsure about how he deals with the Countries property. You could argue both sides: Wrapping the Countries list in the SelectList prepares the data for the view, much like you create a viewmodel DTO to pass your data. On the other hand, it somehow feels like you're specifically manipulating the data to be used in a dropdown list, limiting the way the view deals with your data from the controller. I feel this is a bit of a gray area on the separation of concerns between the view and the controller, and I can't really decide which way to go. Are there any best practices for this?

PS: To keep it simple, let's assume the default ASP.NET MVC context, so basically your out of the box project. Default view engine and all that jazz.

+7  A: 

In MVC (at least this flavor of it), one of the controller's responsibilities is to prepare the data for the view. So I think it is perfectly acceptable to prepare a specific model for the views consumption that implies it will be used in a drop-down. In this case the controller is just making it easier for the view and in fact prevents awkward code from having to otherwise be trickling into the view. It also keeps one from having those magic strings in the ViewData like VieData["Countries"].

So to sum up, while it may seem that there is some gray area in terms of responsibilities, ultimately that is the job of the controller: to interact with the view and to transform the domain model into other models that are easier to consume by the view.

Trevor de Koekkoek
yeah, I think you're right. IF there would be need for another representation of the countries list in the view, you'd basically create another view DTO for that, right?
Erik van Brakel
Probably. Although perhaps the SelectList can be represented by a different UI construct like maybe a list of check boxes or something. Maybe a different html helper method could still use a SelectList and output something else.
Trevor de Koekkoek
+1 Using view models in this way removes even more logic from the view, which is always desirable.
Richard Szalay
+4  A: 

Some suggest that having one all-encompassing view model per view is ideal (dubbed Thunderdome Principal).

Tim Scott