Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 847
Şafak Gür Avatar asked Sep 30 '22 22:09

Şafak Gür


1 Answers

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.

like image 184
m0sa Avatar answered Oct 03 '22 11:10

m0sa