Adding Custom Namespaces to Razor Views

I’ve recently been working on a new web site using ASP.net 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:

<system.web.webPages.razor>
 <pages pageBaseType="System.Web.Mvc.WebViewPage">
  <namespaces>
   <add namespace="Base.ViewModels" />
  </namespaces>
 </pages>
</system.web.webPages.razor>

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.