Search code examples
asp.net-corenavigationblazor.net-8.0

NavigationLock is not working with blazor .net 8 projects


In the previous version (.NET 7), I had no issues using the NavigationLock component. However, after upgrading to .NET 8, I'm encountering a problem where NavigationLock does not seem to trigger any events. To troubleshoot this, I created a new project using the standard template pages and implemented

I NavigationLock as I usually would. Despite this, the expected events are not being activated.

This is the code:

@page "/counter"
@rendermode InteractiveServer
@inject IJSRuntime js

<PageTitle>Counter</PageTitle>
<NavigationLock OnBeforeInternalNavigation=this.OnNavigationAway ConfirmExternalNavigation></NavigationLock>

 <h1>Counter</h1>

 <p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
    async Task OnNavigationAway(LocationChangingContext context)
    {

        var confirmed = await ShowConfirmationDialogAsync();
        if (!confirmed)
        {
            context.PreventNavigation();
        }

    }

    private async Task<bool> ShowConfirmationDialogAsync()
    {
        var s = await js.InvokeAsync<bool>("confirm", "Caught this navigation event! Do you want to continue?");
        return s;
    }
}

Can you help me? Thanks in Advance.


Solution

  • I created a new project using the standard template

    You need to define which options you used. It's important.

    I'm guessing you chose the interactivity location as "Per page/component": this answer is based on that assumption.

    When you choose "Per page/component" App, Router, MainLayout all run in static SSR mode on the Server. For NavigationLock to work it needs to interact with and receive events through the NavigationManager from the Router. The router and Navigation Manager instance runs on the Server in the Http Request context [with a lifetime scoped to the life of the request], NavigationLock runs in the Hub Session context on the server. They are different instances running in different scoped service containers: there's no connection and therefore no events.

    For NavigationLock to work you need to move Interactivity global. Try building a new application from the template, choose Global interactivity, and then re-test.

    See this commentary for more detail: - https://github.com/ShaunCurtis/Blazor.ExploreRendering/blob/master/Documents/Going-For-Broke.md