Think of the Children – Base View Pages in ASP.NET MVC

One common practice emerging in ASP.NET MVC sites is the user of a custom base controller supertype that takes care of global, basic, controller-related concerns.  So rather than all controllers in your application inheriting from System.Web.Mvc.Controller, you can roll your own that inherits from that, and then derive your own controllers from the new base type.

Application Controller in UML

For example, here’s a very simple base controller that gets logging out of the way so all of your controllers get logging for free.  Here’s an example of a controller that handles dependencies for logging (using MVC3′s dependency injection):

So that’s cool.  But did you know you could do the same thing with views?

All you have to do is create a type that derives from System.Web.Mvc.WebViewPage<T>, and then include anything you want to happen on views that inherit from it.  Here’s what some code for it would look like:

The only thing you have to do is wire it up in any web.config (or any area’s web.config) like this to have it take effect:

But, now that I’ve shared that, be careful, this is a loaded gun.  Even though you could insert some logic here, this is really best for setting some view properties so that they’re easily accessed through something like the ViewBag.  It’s super convenient, but It’s for view-specific concerns only.  If you find yourself writing conditional logic or take any dependencies, you should probably be afraid – very afraid.

Basically, don’t resurrect the aspx code-behind.  Please.  For all the future developers working with your code.  Think of the children.