Add namespace to all views in ASP.NET MVC 6

asp.net-core, asp.net-core-mvc

Solution

For <= beta3 bits (what you're most likely using) you should add an `@using` statements to your _ViewStart.cshtml. Aka:

_ViewStart.cshtml: `@using MyProject.WebUI.Helpers`

If you don't have a _ViewStart.cshtml you can create one and just make sure it's in the same path or parent path of the view you want it to affect.

For beta4 bits, this functionality was moved to a new file called _GlobalImport.cshtml; _ViewStart.cshtml was transitioned back to its original functionality (just running code, not inheriting directives). Therefore:

_GlobalImport.cshtml: `@using MyProject.WebUI.Helpers`

For beta5 bits, _GlobalImport.cshtml was renamed to _ViewImports.cshtml

Problem

I’m using MVC 6 and would like to be able to access a particular namespace globally from all of my Razor views. In MVC 5 this was fairly simple; I’d just add the following code to my `~/views/web.config` file: ``` <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <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.Optimization"/> <add namespace="System.Web.Routing" /> <add namespace="MyProject.WebUI" /> <add namespace="MyProject.WebUI.Helpers" /><!-- Added this line --> </namespaces> </pages> </system.web.webPages.razor> ``` Where I’ve added access to the `MyProject.WebUI.Helpers` namespace. In ASP.NET 5, and therefore MVC 6, the `web.config` file has be done away with, so I’m not sure how to go about doing this any more. I’ve tried searching for an answer, but all I can find is how to do it in current versions of ASP.NET rather than v5. Any ideas? Edit: Clarified which `web.config` file I would have used.

Original source