In a Blazor EditForm, when do you pass an EditContext instead of a Model, and what changes when you handle OnSubmit yourself?
answer
- one or the other, never both
- EditContext built only when Model changes
- OnSubmit means you call Validate()
- ValidationMessageStore for your own messages
- IsModified, MarkAsUnmodified, OnFieldChanged
basics
~10 sPass Model when EditForm may build the EditContext itself; pass your own EditContext when code needs it: custom message stores, modified-field checks or field-change events. OnSubmit replaces OnValidSubmit/OnInvalidSubmit, so you call Validate() yourself.
solid answer
~40 s`EditForm` takes exactly one of `Model` or `EditContext`; supplying both, or neither, throws an `InvalidOperationException` when parameters are set. With `Model`, the form creates `new EditContext(Model)` and replaces it only when a different model instance arrives, which also resets modified state and messages. You construct the `EditContext` yourself when the component needs it outside the markup: a `ValidationMessageStore` for errors the server returns, `IsModified()` or `MarkAsUnmodified()` for unsaved-changes logic, or `OnFieldChanged` to react to edits. `OnValidSubmit` and `OnInvalidSubmit` let `EditForm` run `Validate()` and choose the callback; `OnSubmit` hands you the `EditContext` unvalidated, so you call `Validate()` and decide. Combining `OnSubmit` with either of the other two throws.
code
razor · 27 lines@rendermode InteractiveServer
@inject ShiftService Shifts
<EditForm EditContext="editContext" OnSubmit="BookAsync">
<DataAnnotationsValidator />
<InputText @bind-Value="booking.Email" />
<ValidationMessage For="() => booking.Email" />
<button type="submit">Book shift</button>
</EditForm>
@code {
private readonly ShiftBooking booking = new();
private EditContext editContext = default!;
private ValidationMessageStore serverErrors = default!;
protected override void OnInitialized()
{
editContext = new EditContext(booking);
serverErrors = new ValidationMessageStore(editContext);
editContext.OnFieldChanged += (_, e) => serverErrors.Clear(e.FieldIdentifier);
}
private async Task BookAsync(EditContext context)
{
serverErrors.Clear();
if (!context.Validate()) return;
if (await Shifts.TryBookAsync(booking)) return;
serverErrors.Add(() => booking.Email, "This volunteer already holds a shift that day.");
context.NotifyValidationStateChanged();
}
}go deeper
Remember that EditForm takes Model or EditContext, never both, and that OnValidSubmit runs only when validation passes.
Explain when EditForm builds a new EditContext, why OnSubmit cannot be combined with the valid or invalid callbacks, and what Validate() returns.
Show how a ValidationMessageStore carries server-side failures to fields, and how clearing it on submit and on field change keeps the form submittable.
Decide where form state lives across a large app: plain Model forms by default, owned EditContexts only where server checks or unsaved-change guards need them.
## Two ways to give EditForm its state An `EditForm` always works through an **`EditContext`**: the object that holds the model, the per-field modified flags, and the validation messages that validators write and message components read. You can let the form create it or create it yourself. | Parameter | Who creates the `EditContext` | Typical use | |---|---|---| | `Model="Volunteer"` | `EditForm`, as `new EditContext(Model)` | Most forms: bind inputs, validate, submit | | `EditContext="editContext"` | Your component, usually in `OnInitialized` | Forms whose code needs the context's API | The two are mutually exclusive. `EditForm.OnParametersSet` throws an `InvalidOperationException` when both are supplied ("requires a Model parameter, or an EditContext parameter, but not both") and when neither is. With `Model`, `EditForm` builds a new context only when the model reference changes. Assigning a fresh `VolunteerForm` instance after a save therefore gives you a clean form: no modified flags and no stale messages. Re-rendering with the same instance keeps the existing context. ## What you gain by owning the EditContext - **`ValidationMessageStore`** - `new ValidationMessageStore(editContext)` is a store of your own. Messages you `Add` sit beside the validator's and show in `ValidationMessage` and `ValidationSummary`; call `NotifyValidationStateChanged()` after adding them so the UI refreshes. - **Modified state** - `IsModified()` for the whole form or `IsModified(() => model.Email)` for one field; `MarkAsUnmodified()` after a save. - **Events** - `OnFieldChanged` fires when an input reports a change, `OnValidationRequested` when `Validate()` runs, `OnValidationStateChanged` when messages change. - **Field state queries** - `GetValidationMessages()` and `IsValid(() => model.Email)` for conditional UI. - **Field CSS** - `SetFieldCssClassProvider` swaps the default `valid`/`invalid`/`modified` classes for a design system's names. ## OnValidSubmit, OnInvalidSubmit and OnSubmit When the form submits, `EditForm` follows one of two paths: 1. If `OnSubmit` has a delegate, it is invoked with the `EditContext` and nothing is validated for you. 2. Otherwise `EditForm` calls `EditContext.Validate()`; a `true` result invokes `OnValidSubmit`, a `false` one invokes `OnInvalidSubmit`. The source's own comment explains why mixing is refused: if you handle `OnSubmit` you own the validation lifecycle, and the framework should not trigger a second validation implicitly. Supplying `OnSubmit` together with `OnValidSubmit` or `OnInvalidSubmit` throws. `OnValidSubmit` and `OnInvalidSubmit` can be combined with each other. In ASP.NET Core 10 `EditContext.Validate()` is synchronous and returns a `bool`: `true` when no message is left in any store, the validator's or yours. ## A trap with your own message store Because `Validate()` looks at **every** store, a message you added after a failed save keeps the form invalid until you clear it. DataAnnotations clears and rewrites only its own messages. The usual pattern is to clear your store at the start of each submit and, for a better feel, clear one field's entry in `OnFieldChanged` when the user edits it. ## The same pattern under static SSR In a statically rendered page there is no component instance between requests, so an owned `EditContext` lives for one request only: - Create it in `OnInitialized` from the model that `[SupplyParameterFromForm]` mapped (after `Model ??= new()`), not from a private field nobody posts into. - Any `ValidationMessageStore` you attach is empty at the start of each request; a server message you add during the POST is rendered in that response and is gone on the next one. - `OnFieldChanged` never fires between requests, because no input talks to the server until the next submit. That is why the owned-context pattern pays off most in interactive forms, where the same `EditContext` and its stores persist while the user corrects the form. ## Choosing - Use `Model` plus `OnValidSubmit` when the attributes say everything and the save cannot fail per field. - Use your own `EditContext` plus `OnSubmit` when a server check (an email already registered for a shift, a slot already taken) must land on a field, or when the page needs modified-state logic. - Expect a rebuild when the context changes: assigning a new `EditContext` (or a new `Model`) makes `EditForm` tear down and recreate its child components. `InputBase` and `DataAnnotationsValidator` refuse a context swapped underneath them while they live, which is why the form recreates them instead.
- After a failed booking adds a message to your ValidationMessageStore, the user fixes the field but the form still never reaches the save; why?`EditContext.Validate()` returns `true` only when no message remains in any store. DataAnnotations clears and rewrites its own store, not yours, so the server message keeps the form invalid. Clear your store at the start of each submit, or per field from `OnFieldChanged`, then call `NotifyValidationStateChanged()` so the UI updates.
- How do you reset an EditForm to a clean state after a successful save?With `Model`, assign a new model instance: `EditForm` sees a different reference and builds a fresh `EditContext`, so modified flags and messages are gone. With your own context, create a new `EditContext` for the new model, or keep the values and call `MarkAsUnmodified()` if only the modified flags must reset.
- You can pass both Model and EditContext so the form has a fallback.
- OnSubmit runs only after validation has passed, like OnValidSubmit.
- Combining OnSubmit with OnInvalidSubmit lets you handle both outcomes.
- Validate() ignores messages added through your own ValidationMessageStore.
- Re-rendering an EditForm with the same Model creates a new EditContext.