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.
There are two ways to add namespaces: Put @using namespace at the top of the page. Put all the namespaces in Views\Web. config.
Right click the Views\HelloWorld folder and click Add, then click MVC 5 View Page with Layout (Razor). In the Specify Name for Item dialog box, enter Index, and then click OK. In the Select a Layout Page dialog, accept the default _Layout. cshtml and click OK.
The _ViewImports. cshtml file for an ASP.NET Core MVC app is typically placed in the Pages (or Views) folder. A _ViewImports. cshtml file can be placed within any folder, in which case it will only be applied to pages or views within that folder and its subfolders.
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
Add your namespaces to the_ViewImports.cshtml
file (it's under the Views folder).
Example file:
@using Microsoft.AspNetCore.Identity
@using Jifiti.Registry.Web.Models.AccountViewModels
@using Jifiti.Registry.Web.Models.ManageViewModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With