Typesafe viewmodel for MVC frameworks

Ever since I was working with MVC projects, looking at sample code even from Microsoft, I always wondered why everyone is using ViewBag and other “unsafe” techniques for the data to be displayed. I would have sticked to developing PHP applications if I wanted to do that. (And maybe even some PHP frameworks might do a better job than MS from this perspective.)

Now I came up with a very simple solution that I will be using in the future whenever possible: The view-model basically consists of three classes:

  • ViewBase
  • PageBase
  • ContentBase

With this simple setup, there is no need to use the dynamic ViewBag or other constructs that can lead to runtime errors when changes are done to the controller or to the model. Every property can be checked at compile-time for the template _Layout.cshtml as well as for every view.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.