How to set the layout, base class and applications for all kinds?

In MVC 5, I can set the default base class and use it 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?

+4
source share
2 answers

As reported in this github issue in CTP3, this cannot be done through configuration. However, you can 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 do not get intellisense with this approach, since the editor always uses the original MvcRazorHost class.

alpha4 vNext , ( - @inherits , , ) _ViewStart.cshtml, .

+4

2017-1-14, Razor Directives , :

@inherits , Razor

@inherits TypeNameOfClassToInheritFrom

, , Razor:

using Microsoft.AspNetCore.Mvc.Razor;

public abstract class CustomRazorPage<TModel> : RazorPage<TModel>
{
    public string CustomText { get; } = "Hello World.";
}

Razor <div>Custom text: Hello World</div>.

@inherits CustomRazorPage<TModel>

<div>Custom text: @CustomText</div>
0

All Articles