Şafak Gür
Şafak Gür

Reputation: 7355

How to set layout, base class and usings for all views?

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?

Upvotes: 6

Views: 3103

Answers (2)

JJS
JJS

Reputation: 6678

as of 2017-1-14, the documentation on Razor Directives says this is supported:

The @inherits directive gives you full control of the class your Razor page inherits

@inherits TypeNameOfClassToInheritFrom

For instance, let’s say we had the following custom Razor page type:

using Microsoft.AspNetCore.Mvc.Razor;

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

The following Razor would generate <div>Custom text: Hello World</div>.

@inherits CustomRazorPage<TModel>

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

Upvotes: 0

m0sa
m0sa

Reputation: 10940

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.

Upvotes: 4

Related Questions