5
votes

With previous versions of Blazor all files were cshtml pages and were able to use _layout similar to MVC projects - all was well.

But now in the new .NET Core 3.0 release Blazor template switched to *.razor files which are razor components (not razor pages). And the layout is now Shared/MainLayout.razor and is applied via routing in App.razor file:

<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />

So this creates confusion. We're still able to add razor pages (.cshtml files) to the project but they do not get the layout applied. It would be a pain to create and maintain 2 separate identical layouts, 1 for razor pages and 1 for razor components. I was unable to find any guidance for this.

Is there any way to apply razor component layout (Shared/MainLayout.razor) to razor pages (.cshtml files) inside the same project? Of if not, what is the recommended approach?

3
having similar issue as I have had to scaffold some identity in order to alter the login and other pages. There doesn't seem to be a way to inherit the layout as you stated. Did you ever find a way around this?hal9000

3 Answers

1
votes

I currently have the same problem and it's really annoying. Would also be interested in a solution for this. I can't even load the layout with

@{

    Layout = "shared/MainLayout.razor";
}

because it expects a file with the name MainLayout.razor.cshtml then.

1
votes

The quick answer is no. Currently you can load Razor Components into a Razor Page but can’t load a Razor Page in a Razor Component. This is stated in the official docs.

I’m not sure there is a recommended approach as such - Except to try and refactor to Razor Components as much as possible, if using components everywhere is your goal.

If you want to keep a mix then I would suggest sticking with Razor Pages as pages (hope that makes sense) and only use components within those pages. That way you would only need the one Layout type.

1
votes

in the head of your _Layout page add

<base href="~/" />

in the bottom of body add

<script src="_framework/blazor.server.js"></script>

then in your _Host.cshtml file add

@{
    Layout = "_Layout"; //your Layout name
}

for more information follow this link