Alex Rivera | Logout

Should I reuse view models in different views?

Asked 2012-08-30T21:19:26.427
15

I noticed that I have views that need the same information like others. But sometimes you need 5 properties of the view model and sometimes only 2.

Do you share such view model over many views or do you create a separate view model for each view or maybe do you prefere an inheritance or composition strategy?

For me there are some disadvantages for sharing view models:

  1. Principle of Least Surprise: It is strange to fill only 2 properties of 5 of a view model and get null reference exception, because you don't want to query additional data of the database. When the view model has 5 properties I expect that all are filled. The exceptions prove the rule.
  2. Separation of Concerns/Single Responsibility Principle: The view model cluttered up on complex sites, because you have to suit different needs for each view. If logic is involved its getting more complex, too.

What do you think? How do you handle such circumstances?

Edit
Report

1 Answer

3

Definitely one ViewModel per View, imho.

As your application grows in complexity shared ViewModels will tend to grow, and it doesn't feel great to pass an object with 50 properties to a View when all it needs is one property.

Also, sometimes you may want to add extra properties in your ViewModel that are absolutely specific to your View and that you don't need in other Views. Say you have a CSS class that depends on properties from the ViewModel. Instead of writing if else statements in your View, you create a property in the ViewModel that returns the correct css class based on whatever business rules you have. This way you make the View as slim as possible and with a dedicated ViewModel you are not sharing a CSS class name with Views that don't really care about it.

answered 2012-08-30T22:16:05.717

Your Answer