Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 41 ยท Forms and Validation

EditForm Basics

Learn the Blazor EditForm component: binding a model, EditContext, OnSubmit versus OnValidSubmit and OnInvalidSubmit, form names for static rendering, and how a submit flows through the form.

Plain HTML forms post to a server and reload the page. Blazor forms work differently: the EditForm component wraps a model object, tracks which fields the user changed, runs validation and calls your C# handler when the form is submitted. You never read document.getElementById: the form is bound to your data.

Blazor cannot run on this site, so the .razor code is read-only. The runnable C# examples are stand-ins that model what EditForm does (an edit context that tracks changes and a submit pipeline). They are not the real framework.

A first EditForm

HTML
@page "/subscribe"
@rendermode InteractiveServer

<h1>Subscribe</h1>

<EditForm Model="model" OnSubmit="HandleSubmit">
    <label>
        Email
        <InputText @bind-Value="model.Email" />
    </label>
    <button type="submit">Join</button>
</EditForm>

<p>@status</p>

@code {
    private SubscribeModel model = new();
    private string status = "";

    private void HandleSubmit()
    {
        status = $"Thanks, {model.Email}!";
    }

    public class SubscribeModel
    {
        public string Email { get; set; } = "";
    }
}

What happens:

  1. Model="model" gives the form its data object. EditForm creates an EditContext around it.
  2. InputText is one of Blazor's input components. Its @bind-Value writes the typed text straight into model.Email (see two-way data binding).
  3. Pressing the button submits the form. Blazor calls HandleSubmit. No page reload happens in interactive mode.

Model or EditContext

You pass either Model or EditContext, never both:

HTML
<EditForm EditContext="editContext" OnSubmit="HandleSubmit"> ... </EditForm>

@code {
    private EditContext editContext = default!;
    private SubscribeModel model = new();

    protected override void OnInitialized()
    {
        editContext = new EditContext(model);
        editContext.OnFieldChanged += (sender, e) =>
            Console.WriteLine($"Changed: {e.FieldIdentifier.FieldName}");
    }
}

Create your own EditContext when you need to listen to field changes, ask editContext.IsModified(), call editContext.Validate() yourself or attach custom validation. With Model, the form builds one for you.

The three submit callbacks

Parameter When it runs Validation
OnSubmit Every submit You call editContext.Validate() if you want it
OnValidSubmit Only when the model is valid Runs automatically before
OnInvalidSubmit Only when the model is invalid Runs automatically before

OnValidSubmit and OnInvalidSubmit can be used together. Do not combine either of them with OnSubmit: Blazor throws, because OnSubmit takes over the whole decision. The usual choice is:

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

The next lessons fill in DataAnnotationsValidator and ValidationSummary. Without a validator component, every model counts as valid, so OnValidSubmit always fires.

Handlers can be async and may receive the context:

HTML
@code {
    private async Task Save(EditContext context)
    {
        var current = (SubscribeModel)context.Model;
        await Service.SaveAsync(current);
    }
}

Submit flow

flowchart TD
  A["User presses submit"] --> B{"OnSubmit set?"}
  B -->|"yes"| C["Call OnSubmit<br/>you decide about validation"]
  B -->|"no"| D["editContext.Validate()"]
  D --> E{"Valid?"}
  E -->|"yes"| F["OnValidSubmit"]
  E -->|"no"| G["OnInvalidSubmit"]

Using OnSubmit skips the automatic validate-then-branch step.

Static server rendering and FormName

In .NET 8 and later a page can be rendered statically (no interactivity, no @rendermode). An EditForm on such a page performs a real HTTP POST, so Blazor needs to know which form was posted. You add FormName and, for the posted data, [SupplyParameterFromForm]:

HTML
@page "/subscribe"

<EditForm Model="Model" FormName="subscribe" OnValidSubmit="Save">
    <InputText @bind-Value="Model.Email" />
    <button>Join</button>
</EditForm>

@code {
    [SupplyParameterFromForm]
    private SubscribeModel Model { get; set; } = new();

    private void Save() { /* runs on the server during the POST */ }
}

The FormName must be unique on the page. In interactive modes you can leave it out. Antiforgery protection is on by default for these posts: EditForm adds the hidden token for you.

Stand-in: an EditContext that tracks changes

C# Stand-in: EditContext and modified fields

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: the submit pipeline

C# Stand-in: OnValidSubmit versus OnInvalidSubmit

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

  • Passing both Model and EditContext (or neither): an exception at render time.
  • Using OnSubmit together with OnValidSubmit.
  • Expecting validation without a validator component.
  • Replacing model with a new object after the form rendered: the EditContext still points at the old one. Reuse the object or recreate the form with @key.
  • A static page with an EditForm but no FormName.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which two parameters can supply the data of an EditForm?

    EditForm needs exactly one of Model or EditContext. With Model it creates the context for you.
  2. 2. When does OnValidSubmit run?

    EditForm validates first and calls OnValidSubmit or OnInvalidSubmit depending on the result.
  3. 3. What must you do if you use OnSubmit?

    OnSubmit hands the decision to your code, so validation is no longer automatic.
  4. 4. Why does an EditForm on a statically rendered page need FormName?

    A static page receives an ordinary HTTP POST, and the form name identifies the target form.

Summary

  • EditForm wraps a model (or an EditContext) and handles submit.
  • Use OnValidSubmit/OnInvalidSubmit, or OnSubmit when you take control.
  • A validator component is what makes a model invalid.
  • Static pages need FormName and [SupplyParameterFromForm].

Next: Input Components