Adding Custom Namespaces to Razor Views

I’ve recently been working on a new web site using MVC5, and I wanted to be able to reference my view models from my Razor views without having to fully qualify their namespace.

Since I keep my view models in their own ViewModels namespace, all I needed to do was add that to the web.config file located in the Views directory:

 <pages pageBaseType="System.Web.Mvc.WebViewPage">
   <add namespace="Base.ViewModels" />

The namespaces element will already have a number of children, so you can just add your namespace to the end.

If you have any open views in Visual Studio, close and re-open them to pick up the change.  Otherwise, it will show errors and intellisense won’t work unless you continue to fully qualify the view models.