Forms & Events

By Syncfusion®, Inc. · Last updated

Forms and events in Blazor: input components with @bind-Value, one-way and two-way binding, click, mouse, keyboard, focus and change events, EditForm and models, custom inputs, OnSubmit and resetting a form.

What you will learn

  • Bind input components to a model with @bind-Value
  • Tell one-way binding from two-way binding
  • Handle click, mouse, keyboard, focus and change events
  • Build an EditForm, submit it with OnSubmit and reset it

Forms Overview

  • A form is a part of a page where the user types or picks things, like a name, a number or a date.
  • Blazor gives you ready-made input components, like InputText and InputNumber.
  • Each input is linked to a C# value. When the user types, the C# value changes. This link is called data binding.
  • When the user clicks or presses a key, that is an event. Your C# code can react to it.

Real-World Example:

  • Ravi wants an online order form for his tea shop.
  • The customer types a name, picks a tea and a cup size, and chooses a pickup date.
  • When the customer clicks Place order, the page shows "Thanks, Asha! 2 cups of Masala Tea."

Animation: the user types Asha in a text box. A dot carries the text to the C# field order.Name in the code. Then a dot carries it back to the page, which shows Hello, Asha.

The page

Asha Hello, Asha

C# code order.Name = "Asha"

user types Blazor shows the new value

Data binding: the input and the C# value stay the same, in both directions.

Form Components and Data Binding

  • Blazor's input components are InputText, InputNumber, InputDate and more. Each one draws a normal HTML input.
  • You link an input to a value with @bind-Value, for example <InputText @bind-Value="order.Name" />.
  • Input components must sit inside an <EditForm>. Think of EditForm as the box around the form. You learn it in detail later in this lesson.
  • EditForm needs a model: a C# object that holds the form's values, like order.

InputText and InputTextArea

  • InputText is a one-line text box, for a name.
  • InputTextArea is a bigger box with many lines, for a note.
  • Both work with string values.

In the below example, InputText is linked to order.Name and InputTextArea to order.Note. The text under the form shows both values.

  • Change the name, then press Tab or click outside the box. The greeting changes.

InputText updates the value when you leave the box, not on every key press. That is the normal change event of an HTML input.

InputNumber and InputDate

  • InputNumber is a box for numbers, like int or decimal. It does not accept letters.
  • InputDate shows a date picker. It works with DateTime or DateOnly.

In the below example, InputNumber sets the number of cups and InputDate sets the pickup date. The bill uses both.

  • Change the cups to 3, then click outside the box. The bill changes to ₹60.

InputCheckbox

  • InputCheckbox is a tick box. It works with a bool value: true when ticked, false when not.

In the below example, InputCheckbox is linked to order.Sugar. The text shows "with sugar" or "no sugar".

InputSelect

  • InputSelect is a drop-down list. You write each choice as an <option>.
  • The value of the chosen <option> goes into the linked field.

In the below example, InputSelect is linked to order.Size. The three options are Small, Medium and Large.

InputRadio and InputRadioGroup

  • Radio buttons are round choices. The user can pick only one of them.
  • InputRadioGroup holds the group and is linked to the value.
  • Each InputRadio is one choice, with its own Value.

In the below example, InputRadioGroup is linked to order.Delivery. The two InputRadio choices are Pickup and Home delivery.

  • Value="@("Pickup")" gives the choice a C# string. Writing only Value="Pickup" also works for strings.

InputFile

  • InputFile lets the user choose a file from their computer, like a photo.
  • It does not use @bind-Value. Instead, its OnChange event runs a method when a file is chosen.
  • The method gets the file's name, size and type. It does not need an EditForm.

In the below example, InputFile calls FileChosen when a file is picked. The page shows the file's name and size.

To read what is inside the file, use e.File.OpenReadStream(). It allows 500 KB by default. Pass a bigger limit for bigger files, like OpenReadStream(2_000_000).

One-Way and Two-Way Binding (@bind)

  • One-way binding only shows a value: <input value="@name" />. Typing in the box does not change name.
  • Two-way binding shows the value and changes it when the user types: <input @bind="name" />.
  • @bind works on plain HTML inputs. @bind-Value is the same idea for components like InputText.
  • By default, @bind updates when you leave the box. Add @bind:event="oninput" to update on every key press.

Two panels. One-way: an arrow goes only from the C# field name to the input box. Two-way: arrows go both ways between the C# field and the input box.

One-way: value="@name"

name

input box

Typing does not change name

Two-way: @bind="name"

name

input box

Typing changes name

One-way binding only shows the value. Two-way binding also sends changes back.

In the below example, the first box uses one-way binding and the second uses two-way binding with oninput. Type in each box and watch the last line.

  • Typing in the first box does nothing to name. Typing in the second box changes name at once, and the first box shows it too.

Event Handling

  • An event is something the user does: a click, a key press, a mouse move.
  • You handle an event with @on and the event name, like @onclick="AddCup".
  • After your method runs, Blazor renders the component again, so the page shows the new values.

Animation: a click on the Add cup button sends a dot to the C# method AddCup, which changes cups from 1 to 2. Then Blazor renders and the page shows Cups: 2.

Click: Add cup

AddCup(): cups++

Render Cups: 1 Cups: 2

An event runs your method. Then Blazor renders the new values.

Click Events

  • @onclick runs a method when the element is clicked.
  • To pass a value to the method, use a small lambda (a short inline function): @onclick="() => Order("Masala Tea")".

In the below example, each button calls Order with a different tea name. The page shows the last tea and the number of orders.

Mouse Events

  • @onmouseover runs when the mouse moves onto an element. @onmouseout runs when it leaves.
  • @onmousemove runs as the mouse moves. Its method can take MouseEventArgs, which has the position, like e.OffsetX.

In the below example, the card turns purple while the mouse is over it, and the page shows where the mouse is.

Keyboard Events

  • @onkeydown runs when a key is pressed in an element, like a text box.
  • Its method can take KeyboardEventArgs. e.Key tells you which key, for example "Enter".

In the below example, typing a tea name and pressing Enter adds it to the list.

Focus and Change Events

  • @onfocus runs when the user enters a box (clicks or tabs into it). @onblur runs when the user leaves it.
  • @onchange runs when a value is changed and confirmed, like picking from a list. Its method can take ChangeEventArgs, and e.Value is the new value.

In the below example, the status line shows when the name box has focus, and @onchange reads the size picked in the list.

Use @onchange or @bind on an element, not both. @bind already uses the change event, so the build fails if you add both.

Working with EditForm

EditForm and Model

  • EditForm is Blazor's form component. It draws an HTML <form>.
  • Model is the object that holds the form's values. Each input is linked to one property of the model.
  • It is good practice to put the model class in its own file, like Models/TeaOrder.cs.

EditForm holds a model called order. Three inputs inside the form, InputText, InputNumber and InputSelect, each link to one property of order: Name, Cups and Size.

EditForm Model="order"

InputText

InputNumber

InputSelect

order (model) Name Cups Size

Each input in the EditForm is linked to one property of the model.

In the below example, Models/TeaOrder.cs holds the model class. OrderForm.razor puts three inputs in an EditForm, and the summary shows the whole order.

Custom Input Components (@bind-Value)

  • You can make your own input component and use @bind-Value on it, like the built-in ones.
  • The component needs two parameters: Value (the value it shows) and ValueChanged (an EventCallback it calls with the new value).
  • @bind-Value="order.Cups" sets Value and listens to ValueChanged for you.

In the below example, CupStepper.razor shows − and + buttons. Each click calls ValueChanged, so order.Cups in OrderForm.razor changes.

  • Click + twice. The stepper shows 3, and the bill in the parent shows ₹60.

Buttons inside an EditForm submit the form by default. Add type="button" to buttons that only do something else, like the − and + buttons.

Form Submission

OnSubmit

  • Submitting a form means sending it: the user clicks a button with type="submit" or presses Enter in a box.
  • OnSubmit on the EditForm names the method that runs then.
  • With validation (checking the values), you use OnValidSubmit instead. That runs only when every value is correct.

In the below example, the Place order button submits the form. OnSubmit runs PlaceOrder, which shows a thank-you message.

Form Reset

  • Resetting a form means emptying it, so the user can start again.
  • In Blazor, you reset by giving the model a new, empty object: order = new();. The inputs show the new values at once.
  • Use type="button" on a Clear button, so it does not submit the form.

In the below example, Place order shows a message and then resets the form. Clear only resets it.

  • Click Clear. The name box empties and the cups go back to 1.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
An InputText outside an EditFormInput components work anywherePut input components inside an EditFormAn error: it needs a cascading EditContext
<input value="@name" /> to read typingvalue= is two-wayUse @bind="name"Typing does not change name
A normal button inside an EditFormButtons only run @onclickAdd type="button" to non-submit buttonsThe form submits on every click
@onclick="Order(tea)"You can call the method with a value directlyUse a lambda: @onclick="() => Order(tea)"A build error
A custom input with only ValueValue is enough for @bind-ValueAdd EventCallback<T> ValueChangedA build error on @bind-Value

Check Yourself

Exercises

What to Remember

  • Input components (InputText, InputNumber, InputDate, InputCheckbox, InputSelect, InputRadioGroup) go inside an EditForm and use @bind-Value.
  • InputFile uses OnChange to get the chosen file.
  • value="@x" is one-way. @bind="x" is two-way. @bind:event="oninput" updates on every key.
  • Handle events with @onclick, @onmouseover, @onkeydown, @onfocus, @onblur and @onchange. Event args like KeyboardEventArgs give the details.
  • EditForm takes a Model. A custom input needs Value and ValueChanged for @bind-Value.
  • OnSubmit runs when the form is submitted.
  • Reset a form with order = new();. Give non-submit buttons type="button".

Next: Form Validation