nfplee
nfplee

Reputation: 7977

ASP.NET Core - Set Layout Page Outside of the View

I have an ASP.NET Core 2.0 application and I'm trying to set the layout page a view should use outside of the view. That way I won't have to keep repeating the same code at the top for all of my views.

I can achieve this by inheriting all of my views from the following base class which sets it within the constructor:

public class RazorPage<TModel> : Microsoft.AspNetCore.Mvc.Razor.RazorPage<TModel> {
    public RazorPage() {
        var theme = "Theme1;"
        Layout = $"~/Areas/{theme}/Views/Shared/_Layout" + RazorViewEngine.ViewExtension;
    }
}

This works fine however the name of theme changes based on the current URL. I figured I could do this by accessing the current context, however if I call the Context property within the constructor it returns null.

There doesn't appear an appropriate method to override where I could set the Layout property and have access to the current request context.

Does anyone know an alternative way of doing?

Please note that I am aware I could achieve this with _ViewImports/_ViewStart files but due to the structure of my application it would require me to have duplicate files and also I don't like having business logic within my views.

Upvotes: 2

Views: 935

Answers (1)

nfplee
nfplee

Reputation: 7977

I used an IViewLocationExpander (as suggested by @valery.sntx) to specify where to look for my theme's shared views which changes based on the current URL.

I then auto generated a _ViewStart file using an IFileProvider and simply set it's content to:

@{
    Layout = "_Layout"; 
}

The second part is optional but it saved me from having to create multiple _ViewStart files due to the way my application is designed.

Upvotes: 1

Related Questions