How to add a 'default using' to all cshtml

2019-02-07 21:15发布

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.

4条回答
手持菜刀,她持情操
2楼-- · 2019-02-07 21:46

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>
查看更多
劫难
3楼-- · 2019-02-07 21:58

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
查看更多
Lonely孤独者°
4楼-- · 2019-02-07 22:02

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>
查看更多
SAY GOODBYE
5楼-- · 2019-02-07 22:02

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.

查看更多
登录 后发表回答