Skip to content
Tutorials Center
My learning

Topics

Lesson 21 of 41 ยท Forms and Validation

Form Patterns and Submit State

Build robust Blazor forms: prevent double submits, show loading and success states, reset a form, warn about unsaved changes, edit existing data with a copy, and handle server errors.

You now know the pieces: EditForm, inputs and validation. This lesson combines them into the patterns every real form needs: a submit button that cannot be pressed twice, feedback after saving, clearing the form, editing an existing record without changing it until Save, and warning about unsaved changes.

The .razor code is read-only (Blazor cannot run on this site). The C# stand-ins reproduce the state logic (submit guard, copy-on-edit, dirty tracking) so you can run and study it.

Pattern 1: a submit state machine

A form is in one of a few states: idle, submitting, succeeded, failed. Model it explicitly instead of juggling booleans:

HTML
<EditForm Model="model" OnValidSubmit="Save">
    <DataAnnotationsValidator />
    <ValidationSummary />

    <InputText @bind-Value="model.Title" disabled="@(state == FormState.Submitting)" />

    <button type="submit" disabled="@(state == FormState.Submitting)">
        @(state == FormState.Submitting ? "Saving..." : "Save")
    </button>

    @switch (state)
    {
        case FormState.Succeeded: <p class="ok">Saved.</p> break;
        case FormState.Failed:    <p class="error">@error</p> break;
    }
</EditForm>

@code {
    private enum FormState { Idle, Submitting, Succeeded, Failed }
    private FormState state;
    private string? error;
    private PostModel model = new();

    private async Task Save()
    {
        if (state == FormState.Submitting) return;     // guard against a second click
        state = FormState.Submitting;
        error = null;
        try
        {
            await Posts.CreateAsync(model);
            state = FormState.Succeeded;
        }
        catch (Exception ex)
        {
            error = "Could not save: " + ex.Message;
            state = FormState.Failed;
        }
    }
}

Disabling the button is nice for the user, but the guard inside the handler is what really prevents a double submit: a fast double click can queue two events before the UI updates.

Pattern 2: reset after success

Replace the model and the form's EditContext. The easiest way is to change the key of the form:

HTML
<EditForm @key="formVersion" Model="model" OnValidSubmit="Save"> ... </EditForm>

@code {
    private int formVersion;

    private async Task Save()
    {
        await Posts.CreateAsync(model);
        model = new PostModel();
        formVersion++;                // a new EditForm instance: no old errors, no "modified" flags
    }
}

If you only assign a new model, the old EditContext may still hold the previous model's state.

Pattern 3: edit a copy

When editing an existing record, do not bind the inputs directly to the object in your list. If the user cancels, the list would already show their half-typed changes. Edit a copy and write it back on save:

HTML
@code {
    [Parameter] public Post Original { get; set; } = default!;
    private PostModel draft = new();

    protected override void OnParametersSet() =>
        draft = new PostModel { Title = Original.Title, Body = Original.Body };

    private async Task Save()
    {
        await Posts.UpdateAsync(Original.Id, draft);
    }
}

Records with with make copies short: draft = original with { } (use record classes for models if you like immutability, but bind to a mutable copy).

Pattern 4: dirty tracking and unsaved changes

EditContext.IsModified() tells you whether any field was changed. Use it to enable Save only when something changed, and to warn on navigation (NavigationLock component, see navigation):

HTML
<NavigationLock OnBeforeInternalNavigation="ConfirmLeave" ConfirmExternalNavigation="@editContext.IsModified()" />

@code {
    private async Task ConfirmLeave(LocationChangingContext ctx)
    {
        if (editContext.IsModified() && !await Js.InvokeAsync<bool>("confirm", "Discard changes?"))
        {
            ctx.PreventNavigation();
        }
    }
}

After a successful save call editContext.MarkAsUnmodified() so the warning stops.

Pattern 5: server errors

Validation passed in the browser but the server rejected the request (duplicate, conflict, lost connection). Show the problem next to the form and keep what the user typed. Field-specific problems go into a ValidationMessageStore; general problems go into a message above the button. Never clear the form on failure.

stateDiagram-v2
  [*] --> Idle
  Idle --> Submitting: valid submit
  Submitting --> Succeeded: saved
  Submitting --> Failed: error
  Failed --> Submitting: retry
  Succeeded --> Idle: reset or edit again

Four states are enough for most forms; the transitions say what the UI may do next.

Stand-in: the submit guard

C# Stand-in: ignoring a second click while saving

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Stand-in: edit a copy, track dirty state

C# Stand-in: draft copy and IsModified

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common mistakes

  • Relying on disabled alone to stop double submits.
  • Resetting by assigning a new model without recreating the form.
  • Binding to the list item itself while editing.
  • Clearing the form after a failed save.
  • Showing "Saved" before the awaited call finishes.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What really prevents a double submit?

    Two clicks can arrive before the UI updates, so the handler itself must ignore a second call.
  2. 2. Why edit a copy of an existing record?

    Binding to the original mutates it immediately, so Cancel could not undo anything.
  3. 3. How can you get a brand-new EditForm instance (no old errors or modified flags)?

    A different @key makes Blazor discard the old component and create a new one.
  4. 4. What does EditContext.IsModified() tell you?

    It tracks edits, which makes it useful for unsaved-changes warnings.

Summary

  • Model submit as a small state machine and guard the handler.
  • Reset by recreating the form with a new @key.
  • Edit a draft copy, write back on Save.
  • Use IsModified and NavigationLock to protect unsaved work; keep user input on failure.

Next: Routing and Route Parameters