Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor layout component not rendering when using Razor components outside MVC

Tags:

.net

razor

I'm building an .NET console app. This is not a web application. I'm trying to use a new feature in .NET 8 for rendering Razor components outside of MVC as mentioned in this article:

https://learn.microsoft.com/en-us/aspnet/core/blazor/components/render-components-outside-of-aspnetcore?preserve-view=true&view=aspnetcore-8.0

I followed all of the instructions here. Everything works fine. Next, I tried adding a basic layout component and have the original component use the layout. Here is the code for both components:

Documents.razor

@layout Email

<h1>Render Message</h1>
<p>@Message</p>

@code {
    [Parameter]
    public string Message { get; set; }
}

Email.razor

@inherits LayoutComponentBase

<html>
    <body>
        <h1>Test</h1>
        <div>@Body</div>
    </body>
</html>

When I run the program the rendered output is <h1>Render Message</h1><p>Hello from the Render Message component!</p> without any of the layout content. Why is the layout not rendering?

like image 449
Andrew Avatar asked Jul 25 '26 00:07

Andrew


1 Answers

I have fixed the issue. New code is:

Documents.razor:

<LayoutView Layout="@typeof(Email)">
    <h1>Render Message</h1>
    <p>@Message</p>
</LayoutView>
@code {
    [Parameter]
    public string Message { get; set; }
}

Email.razor:

@inherits LayoutComponentBase

<html>
    <body>
        <h1>Test</h1>
        <div>@Body</div>
    </body>
</html>

I also created a _Imports.razor file with this code:

@using Components.Layout

The code is all inside a Components folder. In the Components folder there is a Layout folder. Email.razor is inside that folder. All other files are in the Components folder.

Hope this helps someone in the future.

like image 171
Andrew Avatar answered Jul 27 '26 12:07

Andrew