Skip to content

Saving & server errors

A valid form is only half a save. The server can still say no - with a reason for each field - fail outright, or take long enough that the user gives up on it. SubmitOutcome says which of those happened, SetServerErrors puts a server's complaints on the fields they are about, and CancelSubmit() stops a save in flight. Nothing is retried behind the application's back, and the values are left as they were, so "try again" is simply saving again.

Choose what the pretend server does, then press Save. Refuse answers like an ASP.NET Core ValidationProblemDetails: the username and the email get their own messages, and one about the request as a whole goes to the summary. Fail throws, as a 503 would. Take its time waits five seconds - press Cancel, and with Hold the fields still ticked the form cannot be edited while it waits. Empty the email and the server is never asked at all.
Live form
The server will
Account settings

outcome: None · saving: False · refused by the form's own rules: 0 time(s)

View source
@page "/saving"

<BormView State="_state" ShowErrorSummary="true"
          OnValidSubmit="SaveAsync" OnInvalidSubmit="() => _invalidAttempts++" OnSubmitError="ex => _failure = ex.Message">
    <Actions Context="form">
        @* A button row of the page's own, in place of the built-in one. *@
        <button type="submit" disabled="@form.IsSubmitting">@(form.IsSubmitting ? "Saving…" : "Save")</button>
        <button type="button" disabled="@(!form.IsSubmitting)" @onclick="form.CancelSubmit">Cancel</button>
    </Actions>
</BormView>

<p>@_state.SubmitOutcome</p>   @* None, Invalid, Rejected, Failed, Cancelled or Succeeded *@

@code {
    private readonly AccountSettings _model = new();
    private BormState _state = default!;
    private int _invalidAttempts;
    private string? _failure;

    protected override void OnInitialized()
    {
        var schema = BormBuilder.For<AccountSettings>()
            .Title("Account settings")
            .Field(x => x.Username, f => f.Required())
            .Field(x => x.Email, f => f.Required())
            .Field(x => x.DisplayName)
            .Build();

        _state = new BormState(schema, new BormModelDataAccessor(_model))
        {
            ReadOnlyWhileSubmitting = true      // nothing can change under a save in flight
        };
    }

    // Through BormView the handler is handed only the state; the token that CancelSubmit() and
    // disposing the form signal is state.SubmitCancellationToken.
    private async Task SaveAsync(BormState state)
    {
        var token = state.SubmitCancellationToken;
        await Task.Delay(TimeSpan.FromSeconds(5), token);          // ... await http.PutAsJsonAsync(...) ...

        // A 400 with a ValidationProblemDetails: each key a field, "" the request as a whole.
        state.SetServerErrors(new Dictionary<string, string[]>
        {
            ["$.username"] = ["That username is taken."],
            ["email"] = ["This address belongs to another account."],
            [""] = ["Nothing was saved."],
        });
        // ... or a 503: throw new HttpRequestException("503 Service Unavailable");
    }

    public void Dispose() => _state.Dispose();
}

How a submit ends

SubmitOutcomeWhat happened
InvalidThe form's own rules refused it; the handler never ran. OnInvalidSubmit is raised and focus goes to the first problem.
RejectedThe handler recorded errors with SetServerError or SetServerErrors - a server that said no. Focus goes to the first of them, as for an invalid form.
FailedThe handler threw. The exception is in SubmitError; BormView hands it to OnSubmitError, or lets it escape when that is not set - which on Blazor Server ends the circuit.
CancelledThe handler stopped because CancelSubmit(), or disposing the form, signalled its token.
SucceededValid, and the handler returned without recording an error. IsSubmitSuccessful is true - what a "Saved" banner binds to.

A second press while a save is in flight is ignored, so a double click never posts twice. An error the user makes while the handler runs - letters typed into a number box during a slow save - is theirs to fix, and does not turn a save that went through into a rejected one; ReadOnlyWhileSubmitting prevents that altogether.

A server's errors, on the right fields

SetServerErrors(problem.Errors) takes an ASP.NET Core ValidationProblemDetails's errors as they arrive: keys are matched to fields without regard to case, and the $. System.Text.Json puts in front of its own is dropped; an empty key (or $) is about the request as a whole. Pass a mapPath for an API whose names are not the form's. The messages stay until the field is next validated - the user correcting it, or the next submit - and then the field's own rules speak for it again.

private async Task Save(BormState state, CancellationToken cancellationToken)
{
    var response = await http.PostAsJsonAsync("api/account", _model, cancellationToken);
    if (response.StatusCode == HttpStatusCode.BadRequest
        && await response.Content.ReadFromJsonAsync<ValidationProblemDetails>(cancellationToken) is { } problem)
        state.SetServerErrors(problem.Errors, key => key == "user_name" ? "Username" : key);   // Rejected
    else
        response.EnsureSuccessStatusCode();                                                    // throwing: Failed
}

// await state.SubmitAsync(Save);   - or, through BormView.OnValidSubmit, read state.SubmitCancellationToken

Every message says where it came from - Source is Rule, External (a FluentValidation or DataAnnotations validator), Server or Conversion (text the model cannot hold) - and a rule's Code is its key (required, maxLength, …), the same in every language, for a test or a message component to key off. state.For<T>().SetServerError(x => x.Email, …) names the field by expression.

An unhandled error has occurred. Reload 🗙