views:

63

answers:

2

Consider 2 options for a real-world application that needs to build a model, a composite model if you will, from a variety of sources the choices for for using strongly typed views:

  1. Create a new custom class for the model with a property for each piece of information that needs to be passed to the view stage,

  2. Confine the models to the original domain classes and chain together multiple contollers in using Html.RenderAction.

The downside of option 1 is the need to create lots of "plumbing" classes. The downside of option 2 is a dirty feeling of violating separation of concerns and a more concrete issue of tracking through chains of controllers to find the one that rendered such and such a piece of HTML.

Before ASP.Net MVC came along I previously used Maverick.Net for many years and with it the model was a chunk of XML passed to an XSL view stage. In ASP.Net MVC that would be the equivalent of passing the model to the view stage as a set of key value pairs in the ViewDictionary. The downside of that is no compile time checking of key names but in my experience the key names change very rarely.

An interesting proposed solution to the same issue is to invent dynamic partial classes.

So is using a strongly typed view with ASP.Net MVC a bad approach for composite models and a better, simpler and more productive way to use the crude ViewDictionary approach?

A: 

You might find Automapper a useful tool for creating ViewModels i.e. "composite models" as you describe them, specifically for the presentation layer. Automapper will help reduce a lot of the work involved in creating those mappings between your domain and view models.

This blog post gives a good overview of using Automapper this way.

I think you're right to want to avoid the ViewDictionary in favour of strongly typed views.

Bayard Randel
+3  A: 

On the contrary, you should always seek to use strongly-typed views unless you have no model whatsoever. By creating an explicit view model, you not only gain compile-time checking, but you also improve the intent, discoverability, and readability of your code.

Derek Greer
Totally agree, if you have a view which needs defined values then give it its own model class. Then you know what to pass to it when you re-use the view somewhere else :-)
WestDiscGolf