将名称空间添加到ASP.NET MVC 6中的所有视图 [英] Add namespace to all views in ASP.NET MVC 6

查看:103
本文介绍了将名称空间添加到ASP.NET MVC 6中的所有视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用MVC 6,并且希望能够从我的所有Razor视图中全局访问特定的名称空间.在MVC 5中,这非常简单.我只需将以下代码添加到我的~/views/web.config文件中:

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>

我在其中添加了对MyProject.WebUI.Helpers命名空间的访问权限.

Where I’ve added access to the MyProject.WebUI.Helpers namespace.

在ASP.NET 5(因此是MVC 6)中,web.config文件已被删除,因此我不确定如何继续执行此操作.我曾尝试寻找答案,但我能找到的只是在当前版本的ASP.NET(而不是v5)中如何做到这一点.

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.

有什么想法吗?

阐明了我将使用哪个web.config文件.

Clarified which web.config file I would have used.

推荐答案

对于< = beta3位(您最有可能使用的位),您应该在_ViewStart.cshtml中添加@using语句.又名:

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

_ViewStart.cshtml: @using MyProject.WebUI.Helpers

如果您没有_ViewStart.cshtml,则可以创建一个,并确保它位于您希望其影响的视图的同一路径或父路径中.

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.

对于beta4位,此功能已移动到名为_GlobalImport.cshtml的新文件中. _ViewStart.cshtml已转换回其原始功能(仅运行代码,不继承指令).因此:

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

_GlobalImport.cshtml: @using MyProject.WebUI.Helpers

对于beta5位,_GlobalImport.cshtml重命名为_ViewImports.cshtml

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

这篇关于将名称空间添加到ASP.NET MVC 6中的所有视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆