tracks form changes and warns users before navigation

This commit is contained in:
2025-12-25 23:55:04 -05:00
parent 059a16b958
commit 77b5683804
8 changed files with 156 additions and 8 deletions
@@ -11,6 +11,7 @@
BackButtonUrl="/students" />
<EditForm id="create-student-form" Model="Student" OnValidSubmit="OnValidSubmit" Enhance>
<FormChangeTracker @ref="_formChangeTracker" />
<AntiforgeryToken />
<DataAnnotationsValidator />
<MudGrid>
@@ -29,18 +30,27 @@
<FormActions>
<MudButton ButtonType="ButtonType.Submit" Variant="Variant.Filled" Color="Color.Primary" Form="create-student-form">Create</MudButton>
<MudButton Href="/students" Variant="Variant.Text">Cancel</MudButton>
<MudButton OnClick="HandleCancel" Variant="Variant.Text">Cancel</MudButton>
</FormActions>
@code {
[SupplyParameterFromForm]
private Student Student { get; set; } = new() { TsaYear = 1 };
private FormChangeTracker? _formChangeTracker;
private void OnValidSubmit(EditContext context)
{
_formChangeTracker?.AllowNavigation();
Context.Students.Add(Student);
Context.SaveChanges();
NavigationManager.NavigateTo("/students");
}
private void HandleCancel()
{
_formChangeTracker?.AllowNavigation();
NavigationManager.NavigateTo("/students");
}
}
+11 -2
View File
@@ -20,6 +20,7 @@
@* https://www.mudblazor.com/components/form *@
@* https://medium.com/@husainalbar/applying-mudblazor-for-crud-operations-in-our-blazor-project-a343037a52ef *@
<EditForm method="post" Model="Student" OnValidSubmit="UpdateStudent" FormName="edit" Enhance>
<FormChangeTracker @ref="_formChangeTracker" />
<AntiforgeryToken />
<DataAnnotationsValidator/>
<MudGrid>
@@ -49,7 +50,7 @@
<FormActions>
<MudButton OnClick="UpdateStudent" Variant="Variant.Filled" Color="Color.Primary">Save</MudButton>
<MudButton Href="@(ReturnUrl ?? "/students")" Variant="Variant.Text">Cancel</MudButton>
<MudButton OnClick="HandleCancel" Variant="Variant.Text">Cancel</MudButton>
</FormActions>
@code {
@@ -62,6 +63,8 @@
[SupplyParameterFromForm]
private Student? Student { get; set; }
private FormChangeTracker? _formChangeTracker;
protected override async Task OnInitializedAsync()
{
Student ??= await Context.Students.FirstOrDefaultAsync(m => m.Id == Id);
@@ -75,7 +78,7 @@
// To protect from overposting attacks, enable the specific properties you want to bind to.
// For more information, see https://learn.microsoft.com/aspnet/core/blazor/forms/#mitigate-overposting-attacks.
private async Task UpdateStudent()
{
{
if (Student?.OfficerRole == 0)
Student.OfficerRole = null;
@@ -84,6 +87,8 @@
try
{
await Context.SaveChangesAsync();
_formChangeTracker?.AllowNavigation();
NavigationManager.NavigateTo(ReturnUrl ?? "/students");
}
catch (DbUpdateConcurrencyException)
{
@@ -96,7 +101,11 @@
throw;
}
}
}
private void HandleCancel()
{
_formChangeTracker?.AllowNavigation();
NavigationManager.NavigateTo(ReturnUrl ?? "/students");
}