views:

136

answers:

2

I've seen several posts on StackOverflow and elsewhere discussing the various ways to bring together data from multiple entities into a strongly typed view, these being using the ViewData object or constructing a new custom class that utilizes both entities.

To me it seems that if you are representing some sort of new hybrid entity you would want to make a new class and treat it as such. However, I can see the reason for using view data if you're passing in data for things that aren't necessarily part of the entity you're working with, but are still in your model, such as drop down lists or other UI elements.

I see people advocating one or the other for various reasons and I was wondering is there any rule as to when to use one over the other?

+8  A: 

Once I went with typed ViewDataModels I never ever had the need to put stuff in the ViewData Dictionary and work with magic strings in the View. Magic strings feels dirty and very error prone.

What i generally do is create a ViewDataModel class for all my controllers. i.e:

  • HomeController
  • HomeModel
  • HomeViewDataModel
  • Home ActionResult View pages.

all these *ViewDataModel's extend a common ViewDataModel class, useful to pass global site configuration data to the views.

I don't really care what I put in that viewdatamodel, if I need it I make it a property and fill it whenever needed wheter that is some Linq2sql class or an arbitrary menu configuration class.

Even if you don't need extra properties other then a model object it's easier to later on add a property then it is to retype a view. Quite a lot of my ViewDataModel classes consist of 1 property but knowing I can add more without the need to refactor anything is a bliss.

I often think of asp.net mvc as asp.net mvvc as the transporter ViewDataModel classes that transport model and junk(?) data to the view play a huge role.

Martijn Laarman
A: 

I'm not sure it's a really good practice to create ViewModel objects when there's nothing more than the model to return. It just create more objects to garbage collect for the server. I think it's good to use ViewModel but only when you need it. But I agree with the fact that magic strings must be avoided. It creates weaker code that it's harder to maintain later.

mberube.Net