Page prevent navigation

Pablo

Well-known member
Joined
Aug 12, 2021
Messages
95
Programming Experience
10+
Hello,
I'm working on a contact list Blazor app. Everything is going very well, until I tried to add navigation prevent in my insert/update page, if it has missing/unsaved data. I took the code form Google AI, and tried with that code to see if leaving the current page was prevented, and it was not. I attach this code. If I click on any of the NavBar menu items it navigates to them, it doesn't prevent.
Could you give me any guidance to achieve this? Any help would be appreciated.
Regards
Pablo
C#:
Expand Collapse Copy
@page "/index"
@inject NavigationManager NavigationManager

<h3>Index</h3>

<NavigationLock OnBeforeInternalNavigation="HandleInternalNavigation" ConfirmExternalNavigation="@_hasUnsavedChanges" />

@code {

    private bool _hasUnsavedChanges = false;

    // Call this method whenever a change occurs that requires user confirmation before leaving
    private void MarkChangesAsUnsaved()
    {
        _hasUnsavedChanges = true;
    }

    // Call this method when changes are saved
    private void MarkChangesAsSaved()
    {
        _hasUnsavedChanges = false;
    }

    private async Task HandleInternalNavigation(LocationChangingContext context)
    {
        if (_hasUnsavedChanges)
        {
            // You can display a custom dialog here asking for confirmation
            // For example, using a Blazor component library's dialog
            bool confirmed = await ShowConfirmationDialog("You have unsaved changes. Are you sure you want to leave?");

            confirmed = false;
            if (!confirmed)
            {
                context.PreventNavigation(); // Prevent the navigation
            }
            else
            {
                // Optionally, save changes or handle them as needed before proceeding
                _hasUnsavedChanges = false; // Reset the flag after confirmation
            }
        }
    }

    // Example of a placeholder for a custom confirmation dialog
    private Task<bool> ShowConfirmationDialog(string message)
    {
        // Implement your custom dialog logic here (e.g., using a modal component)
        // For demonstration, returning a simple Task.FromResult(true) or false
        return Task.FromResult(true); // Replace with actual dialog interaction
    }
}
 
Just for testing purposes, what happens when you change line 6 to:
<NavigationLock OnBeforeInternalNavigation="HandleInternalNavigation" ConfirmExternalNavigation="true" />
 
Just for testing purposes, what happens when you change line 6 to:

<NavigationLock OnBeforeInternalNavigation="HandleInternalNavigation" ConfirmExternalNavigation="true" />
With true or false it happens the same, it doesn't prevent leaving the page.
 
When set to true, set a breakpoint on HandleInternalNavigation(). Is the method even called?
 
Back
Top Bottom