MVC View Model Inheritance, April 27, 2013 MVC is a tool that gives developers a lot of freedom to architect a solution nearly any way imaginable. This can be both a blessing and a curse; many projects become more complex than they need to be. For me, one of MVC's most interesting features is the so-called "strongly typed view". Instead of having a hodge-podge of public properties in the code-behind file for an aspx file, a strongly typed view allows us to specify a .net class that contains the data that should be displayed on the view. Such as class is called a "View Model". In my mind ,this is an unfortunate minomer because "View" and "Model" both mean something else in MVC and this is different.

Alternatively, the "ViewBag" may be used, which is basically an object dictionary. I avoid the ViewBag like the plague. If I use the ViewBag and someone else must maintain my code, that developer must make an effort to figure out what is supposed to be in the ViewBag (on every single page). With a View Model, the developer has an easy reference telling him what that class is supposed to contain.

That being said, in the default layout view provided in Visual Studio 2010, the ViewBag is used to specify the page title. Since my other page views reference the layout, it would appear that I am stuck with using the ViewBag for the page title (and presumably whatever else I want to be able to manipulate on the layout page).

I believe that I have found a great solution to this problem: make my View Models inherit a base class. Note that unlike controller classes, View Model classes do not inherit any base class from the MVC framework, so I may easily define a base View Model class like in the code to the left:

Note that this View Model has two properties: PageTitle and LowVision. Once we designate that BaseViewModel is the View Model for the layout page, we can refer to the page's title as Model.PageTitle. All I need to do is make the View Models for the views that use this layout inherit this class.

I've also added another property called LowVision. Suppose for the sake of discussion that I have some special CSS that should be included in the view only for specific users. When my View Models inherit from this one and the layout view is programmed to read the LowVision property, all I need so is set the value appropriately for each view that uses the layout.

Another advantage that I see in this inheritance is that if I need to add a new property to BaseViewModel, I can specify a default value in the constructor. The views that use the default value need not specify it, so I can refer to it only on new views.

In short, I find that using View Model inheritance in this style eliminates the need to use the ViewBag on layout pages in my MVC applications and helps to keep data organized.