In my Blazor Server project, I have a breadcrumb in the AppLayout
that works for all pages (menu items):
<ul id="breadcrumbs" class="breadcrumbs">
<li><a href="#">Home</a></li>
@if (CurrentModuleState != null)
{
<li>@CurrentModuleState.Descriptor.Name</li>
}
</ul>
I need to modify the breadcrumb for just one specific page. To achieve this, I assigned an ID to the breadcrumb and used JavaScript to update it dynamically:
<script>
window.updateBreadcrumb = function (breadcrumbText) {
var breadcrumbElement = document.getElementById("breadcrumbs");
if (breadcrumbElement) {
breadcrumbElement.innerHTML = breadcrumbText;
}
}
</script>
The issue is that once the JavaScript changes the breadcrumb, it stays modified even after navigating to other pages, and the default breadcrumb logic in the AppLayout
no longer works as expected.
How can I ensure the JavaScript change only applies to the specific page and that the default breadcrumb behavior is restored on other pages?
No need to resort to JS, just use Sections.
Here's a Demo Layout. I have no idea what CurrentModuleState
is, so I've just used simple strings to demonstrate the pattern.
Note I've defined both a SectionOutlet
and a default SectionContent
for the default content.
@inherits LayoutComponentBase
@using Microsoft.AspNetCore.Components.Sections
<div class="page">
<div class="sidebar">
<NavMenu />
</div>
<main>
<div class="top-row px-4">
<SectionOutlet SectionName="header-breadcrumb" />
<a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
</div>
<article class="content px-4">
@Body
</article>
</main>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="" class="reload">Reload</a>
<a class="dismiss">🗙</a>
</div>
<SectionContent SectionName="header-breadcrumb">Fred</SectionContent>
You can now change this on any page by defining a custom SectionContent
. In this example the Counter
page:
@page "/counter"
@using Microsoft.AspNetCore.Components.Sections
<PageTitle>Counter</PageTitle>
<SectionContent SectionName="header-breadcrumb">Joe</SectionContent>
<h1>Counter</h1>
//...