Saturday, 23 February 2013

ASP.NET MVC Consolidating "Usings" in Views/Web.config

Something I came across yesterday that you may find useful as an ASP.NET MVC developer. If you find yourself having to include the same set of "usings" across many of your razor views, then you can consolidate them and put them in the Web.config that sits under the Views folder.

The specific config element you're interested in is system.web.webPages.razor/pages/namespaces. It's a case of just creating an entry for each of your commonly used namespaces and then you don't need to worry about adding @using's or fully qualified class names in your views to resolve commonly used types.


<pages pageBaseType="System.Web.Mvc.WebViewPage">
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Optimization"/>
    <add namespace="System.Web.Routing" />
    <add namespace="MyMvcApp.Models.ViewModels" />

If you're using the WebForms (ASPX) view engine then the equivalent place to add your global usings is in the same Web.config but within the system.web/pages/namespaces element.