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.