I'm creating my first MVC.Net application and I find myself including @using Gideon.Core.Mvc;
on almost every page. Is it possible to add it by default to all pages?
In Asp.Net I'm able to add default stuff for controls to the web.config, hopefully it can be done for MVC.Net as well.
You can add them in the <system.web.webPages.razor>
section in Views/Web.config
.
Here is the default:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.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.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
Add them in the Views/Web.config
. Add your namespace to the bottom:
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="Gideon.Core.Mvc" />
</namespaces>
</pages>
</system.web.webPages.razor>
For .Net Core Users if you create a vanilla web project you can import default namespaces by adding the
_ViewImports.cshtml
File within your Pages folder.
And define your default namespaces within.
@using test
@namespace test.Pages
Since this question is high on google, let me add an alternative solution which is area compatible.
Create a new class called PreApplicationStart
(or any other name you want).
public class PreApplicationStart
{
public static void InitializeApplication()
{
System.Web.WebPages.Razor.WebCodeRazorHost.AddGlobalImport("insert.your.namespace.here");
}
}
In Properties\AssemblyInfo.cs
add following line:
[assembly: System.Web.PreApplicationStartMethod(typeof(PreApplicationStart), "InitializeApplication")]
With this the namespace is available in every view in the project (including views within areas). Adding the namespace to web.config
has this flaw, that if you use areas, you end up having to add the namespace to every web.config
file in each area.