Reputation: 789
For login, registration pages I'm using MVC .cshtml views. I have a Blazor component as my layout for Blazor pages and I want to apply it for mvc pages as well and avoid duplicate my layout. Is that possible? if not what's the solution?
I َAppreciate any help and solution
Upvotes: 3
Views: 2269
Reputation: 135
Chris guided us to the doc to refer to (Thank you, Chris!). For those who still wish to try using Blazor-style layouts in MVC or Razor page projects, follow all instructions in the doc Chris pointed out and you can get a view like:
The above is rendered with a Blazor layout component (CustomLayout1.razor
):
@inherits LayoutComponentBase
<div class="container-fluid border border-primary p-3">
<p>CustomLayout1</p>
<div class="container-fluid border border-danger p-3">
@Body
</div>
</div>
and a routable Blazor component which uses the custom layout (LayoutTest_Body.razor
):
@page "/test"
@layout Views.Shared.CustomLayout1
<p>LayoutTest_Body</p>
As a sample for nested layouts, I added another Blazor layout component (CustomLayout2.razor
) which is embedded into CustomLayout1:
@inherits LayoutComponentBase
@layout Views.Shared.CustomLayout1
<div class="container-fluid border border-warning p-3">
<p>CustomLayout2</p>
<div class="container-fluid border border-info p-3">
@Body
</div>
</div>
and changed the @layout
of LayoutTest_Body.razor
from CustomLayout1
to CustomLayout2
:
@page "/test"
@layout Views.Shared.CustomLayout2
<p>LayoutTest_Body</p>
to get:
Please note that:
LayoutTest_Body.razor
at the first line of which holds @page
directive followed by a unique route string.app.MapBlazorHub();
, template: app.UseEndpoints(endpoints => { endpoints.MapBlazorHub(); });
).App.razor
. In case of MVC project, (i) Create the parameter data and let public IActionResult Blazor()
to pass it to _Host.cshtml
via ViewBag, (ii) Let _Host.cshtml
to pass the parameter data to App.razor
by setting param-[paramname]="@ViewBag.xxxx"
, (iii) Receive the parameter at App.razor
which in turn passes it to descendants as CascadingValue
and finally (iv) Let any descendants to consume it as CascadingParameter
. Passing non-serializable parameter to Blazor components is not allowed at the time of this posting, but creating a dictionary for layout settings and passing it in JSON format could be one solution for a centralized management of various layouts.Upvotes: 1
Reputation: 239430
This is covered in the docs for using razor components alongside MVC. Simply put, you don't use Blazor-style layouts. Rather, your MVC layout is utilized by the _Host.cshtml
, and your routeable razor components are loaded within that.
Upvotes: 2