如何为所有视图设置布局,基类和使用?(How to set layout, base class and usings for all views?)

编程入门 行业动态 更新时间:2024-10-23 15:30:01
如何为所有视图设置布局,基类和使用?(How to set layout, base class and usings for all views?)

在MVC 5中,我可以为“Views / Web.Config”中的所有视图设置默认基类和使用:

<system.web.webPages.razor> <pages pageBaseType="SomeCustomPageClass"> <namespaces> <add namespace="SomeNamespace" />

我还可以在“_ViewStart.cshtml”中为所有视图设置默认布局:

@{ Layout = "~/Views/Shared/SomeCustomLayout.cshtml"; }

我怎样才能在MVC 6中做到这些?

In MVC 5, I can set a default base class and usings for all views in "Views/Web.Config":

<system.web.webPages.razor> <pages pageBaseType="SomeCustomPageClass"> <namespaces> <add namespace="SomeNamespace" />

I can also set the default layout for all views in "_ViewStart.cshtml":

@{ Layout = "~/Views/Shared/SomeCustomLayout.cshtml"; }

How can I do any of these in MVC 6?

最满意答案

正如在CTP3 中的这个github问题中所报告的,没有办法通过配置来实现这一点。 但是,您可以使用自定义MvcRazorHost替换默认的MvcRazorHost:

public abstract class MyPage<T> : RazorPage<T> {/*...*/} public abstract class MyPage : RazorPage {/*...*/} public class MvcMyHost : MvcRazorHost { public MvcMyHost() : base(typeof(MyPage).FullName) { } } public class Startup { public void Configure(IBuilder app) { var configuration = new Configuration(); configuration.AddJsonFile("config.json"); configuration.AddEnvironmentVariables(); app.UseServices(services => { services.AddMvc(configuration); services.AddTransient<IMvcRazorHost, MvcMyHost>(); }); // etc... } }

不幸的是,由于编辑器总是使用原始的MvcRazorHost类,因此您无法使用此方法进行智能感知。

在vNext的alpha4 ,您所要求的所有内容(页面基本类型通过 - @inherits指令,使用,布局)将通过_ViewStart.cshtml支持, _ViewStart.cshtml所述。

As reported in this github issue in CTP3 there is no way of doing this via configuration. You can however replace the default MvcRazorHost with a custom one:

public abstract class MyPage<T> : RazorPage<T> {/*...*/} public abstract class MyPage : RazorPage {/*...*/} public class MvcMyHost : MvcRazorHost { public MvcMyHost() : base(typeof(MyPage).FullName) { } } public class Startup { public void Configure(IBuilder app) { var configuration = new Configuration(); configuration.AddJsonFile("config.json"); configuration.AddEnvironmentVariables(); app.UseServices(services => { services.AddMvc(configuration); services.AddTransient<IMvcRazorHost, MvcMyHost>(); }); // etc... } }

Unfortunately you don't get intellisense with this approach, since the editor always uses the original MvcRazorHost class.

In alpha4 of vNext everything you've asked for (page base type via - @inherits directive, usings, layout) will be supported via _ViewStart.cshtml as discussed here.

更多推荐

本文发布于:2023-07-20 02:58:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1192100.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:视图   何为   布局   set   layout

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!