Global Namespace Includes with MVC and Razor

PUBLISHED ON MAR 7, 2011

While I’m loving MVC3 and the Razor view engine, I was sorely disappointed when I couldn’t use the system.web/pages/namespaces collection in web.config to add global namespace includes.

After a bit of hunting and looking through the web.config files underneath the views folder (in each Area), I found that this can be accomplished by adding the following to the root web.config file:

<configuration>
<configSections>
...
...
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
...
...
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
...
...
</configuration>
view raw web.config hosted with ❤ by GitHub

Now you can add any namespaces you require under the new razor namespaces section.

TAGS: .NET, MVC, RAZOR