Question

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?

Was it helpful?

Solution

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, that is:

  • 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 whether that is some LINQ to SQL class or an arbitrary menu configuration class.

Even if you don't need extra properties other than a model object, it's easier to add a property later on than 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 MVVM as the transporter ViewDataModel classes that transport model and junk(?) data to the view play a huge role.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top