I'm using an EditContext to track changes in a form, and I show a confirmation dialog using ConfirmAsync() if there are unsaved changes when navigating away.
The logic below is implemented in a different page, which is used by multiple form pages to prevent the user from navigating away when there are unsaved changes on the form:
public async Task<bool> GetConfirmation(){ if (ParentForm != null && ParentForm.EditContext.IsModified()) { return await dialogs.ConfirmAsync("You have unsaved changes. Do you want to leave?", "Confirm", "Leave", "Cancel"); } return true;}In my component’s OnInitializedAsync, I call GetUserData(), which loads user data. But that method internally calls GetConfirmation() as part of some logic. Because EditContext.IsModified() returns true during initialization (probably due to binding), the dialog shows up on page load, which is not desired.
This happens even when no validation messages are shown, so checking for EditContext.GetValidationMessages().Any() isn't reliable either.
Below is a sample initialization of the page and how I call this method from the parent form.
<NavigationConfirmationDialog @ref="@refNavigationConfirm" ParentForm="@formRef" /> private async Task GetUserData(int userId) { if (!await refNavigationConfirm.GetConfirmation()) { //Some code here } }Constraints:
- This logic is shared across multiple pages, so I don’t want to put page-specific workarounds.
- I’m looking for a centralized solution — ideally something I can control within the GetConfirmation() method or in a shared service/component.
How can I prevent the confirmation dialog from being shown during the initial data load (e.g. OnInitializedAsync) but still trigger it correctly for actual unsaved changes afterward?