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
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#:
@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
}
}