Skip to content

Fix menu problem in templates - #68768

Merged
dariatiurina merged 6 commits into
dotnet:mainfrom
dariatiurina:68677-menu-problem
Sep 1, 2026
Merged

dariatiurina merged 6 commits into
dotnet:mainfrom
dariatiurina:68677-menu-problem

Conversation

@dariatiurina

@dariatiurina dariatiurina commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

Fix menu problem in templates

Mobile nav menu stays open after navigation in interactive render modes

Description

In .NET 11 the Blazor Web App template's mobile nav menu no longer collapses after you pick a page, but only when an interactive render mode is used (Interactive Server, WebAssembly, or Auto). Static SSR is unaffected.

#63828 removed the inline onclick="document.querySelector('.navbar-toggler').click()" from .nav-scrollable (to avoid an inline event handler for CSP) and replaced it with a NavMenu.razor.js module that resolved the element once and bound a listener to it:

const navScrollable = document.getElementById("nav-scrollable");
navScrollable.addEventListener("click", ...);

That module runs during prerendering, so the listener is attached to the prerendered #nav-scrollable element. On a root component's first interactive render BrowserRenderer.updateComponent calls detachEventHandlersFromElement and emptyLogicalElement, discarding the prerendered markup and inserting new DOM nodes, so the listener is left on a detached element where it never fires again. Being an ES module, it is not re-evaluated to rebind. Under static SSR the element is never replaced, which is why that mode still works.

The fix wraps the toggler and the menu in a <nav-menu> custom element and moves the listener into its lifecycle callbacks:

customElements.define('nav-menu', class extends HTMLElement {
    #closeMenu = event => {
        const toggler = this.querySelector('.navbar-toggler');
        if (toggler?.checked && event.target.closest('.nav-scrollable')) {
            toggler.checked = false;
        }
    };

    connectedCallback() {
        this.addEventListener('click', this.#closeMenu);
    }

    disconnectedCallback() {
        this.removeEventListener('click', this.#closeMenu);
    }
});

customElements.define registers the element once for the document, so whichever <nav-menu> is live gets the handler: the browser upgrades the prerendered element on page load, and fires connectedCallback again on the replacement element Blazor creates during the interactive takeover. The listener stays scoped to the menu instead of document, and no initializer ordering or re-evaluation is involved.

The handler resolves the toggler at click time rather than in connectedCallback, because Blazor inserts an element into the DOM before appending its children, so the subtree is not yet available when the callback runs.

The handler also sets toggler.checked = false instead of calling toggler.click(). click() toggles rather than closes, so on viewports at or above 641px - where the menu is always visible and the toggler is hidden - clicking a nav link used to silently check the toggler, leaving the menu stuck open the next time the window was narrowed.

nav-menu is styled display: contents so the wrapper adds no box of its own and the existing layout, including the .navbar-toggler:checked ~ .nav-scrollable sibling rule, is unchanged.

Changes

  • BlazorWeb-CSharp template: NavMenu.razor wraps the toggler and .nav-scrollable in <nav-menu> and drops the now-unused id="nav-scrollable"; NavMenu.razor.js defines the custom element; NavMenu.razor.css adds nav-menu { display: contents; }.
  • BlazorWebAppGlobal.Client and BlazorWebAppPerPage samples: same change, keeping the duplicated files in sync with the template.
  • Template tests: new VerifyNavMenuCollapsesAfterNavigationAsync helper in BlazorTemplateTest, run as part of TestBasicInteractionAsync.

Testing

VerifyNavMenuCollapsesAfterNavigationAsync resizes the page to 400x800 (below the 641px breakpoint where the menu collapses behind the toggler), opens the menu, clicks the Home link from inside the open menu, and asserts .nav-scrollable becomes hidden. The original viewport is restored in a finally.

The assertion is on .nav-scrollable visibility rather than on the toggler's checked state, so it does not depend on how a given template implements the menu. That lets it run unconditionally for every Blazor template as part of the basic interaction test, gated only on the existing BlazorTemplatePages.Home flag because it navigates Home. It therefore also covers the standalone Blazor WebAssembly template, whose NavMenu uses a C# ToggleNavMenu handler and a collapse class instead of a toggler checkbox.

Through BlazorWebTemplate_Works it runs for the None, Server, WebAssembly and Auto interactivity options against both the built and the published app. The None case is the useful control: it passed before this change and must keep passing.

The assertion reuses the projects those tests already create, build and publish, so it adds no extra template build to the run.

Breaking changes

None. This only changes template and sample content; no product API or behavior outside the generated nav menu markup is affected. Existing apps are unaffected, since template content only applies to newly created projects.

Fixes #68677

@dariatiurina dariatiurina self-assigned this Aug 25, 2026
@dariatiurina dariatiurina added this to the 11.0-rc2 milestone Aug 25, 2026
@dariatiurina
dariatiurina requested a lite review from Copilot August 25, 2026 09:12

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes mobile navigation menus in Blazor Web App templates and samples so they collapse after navigation.

Changes:

  • Uses delegated click handling for resilient menu behavior.
  • Adds responsive test coverage across interactivity modes.
  • Updates corresponding sample applications.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated no comments.

Show a summary per file
File Summary
src/ProjectTemplates/Web.ProjectTemplates/content/BlazorWeb-CSharp/BlazorWebCSharp.1/Components/Layout/NavMenu.razor.js Updates template menu handling.
src/ProjectTemplates/test/Templates.Blazor.Tests/BlazorWebTemplateTest.cs Adds menu-collapse verification.
src/ProjectTemplates/test/Templates.Blazor.Tests/BlazorTemplateTest.cs Adds viewport and navigation test support.
src/Components/Samples/BlazorWebAppPerPage/Components/Layout/NavMenu.razor.js Applies the menu fix to the per-page sample.
src/Components/Samples/BlazorWebAppGlobal.Client/Layout/NavMenu.razor.js Applies the menu fix to the global-interactivity sample.

💡 Add a code-review agent skill for context-aware, tailored reviews. Learn more in the docs.

@dariatiurina
dariatiurina marked this pull request as ready for review August 25, 2026 11:30
@dariatiurina
dariatiurina requested a review from a team as a code owner August 25, 2026 11:30
@dariatiurina

Copy link
Copy Markdown
Contributor Author

After more deep investigation process:

The problem is connected to the transfer from non-interactivity to interactivity. We destroy and rebuild DOM in this process, which means that we do not have listeners that we had before.

Connected to #42561

@PureWeen

Copy link
Copy Markdown
Member

One thing I noticed while comparing this with our version: these test rows use the template’s default InteractivePerPage location. Since AllInteractive defaults to false, the layout containing NavMenu stays static, so the test can pass without exercising the hydration replacement that caused this bug.

I added an explicit --all-interactive Server row locally. With the original listener it fails after navigation because the toggler remains checked (Expected: False, Actual: True), and it passes with the custom element.

Would it make sense to add that case here so the regression test definitely covers the failing path?

Written by Copilot with human help.

@dariatiurina
dariatiurina merged commit 87d1567 into dotnet:main Sep 1, 2026
31 checks passed
@dariatiurina

Copy link
Copy Markdown
Contributor Author

/backport to release/11.0

@github-actions

github-actions Bot commented Sep 1, 2026

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0 (link to workflow run)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Mobile menu remains open after navigation in Blazor Web App interactive render modes (.NET 11)

7 participants