AlexVPerl
AlexVPerl

Reputation: 7996

Blazor .NET Core 3.0 - Can cshtml pages use MainLayout.razor

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?

Upvotes: 9

Views: 2449

Answers (3)

Seyed Reza Dadrezaei
Seyed Reza Dadrezaei

Reputation: 583

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

Upvotes: 2

Chris Sainty
Chris Sainty

Reputation: 8521

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.

Upvotes: 2

d00d
d00d

Reputation: 753

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.

Upvotes: 1

Related Questions