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
InputTextandInputNumber. - 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,InputDateand 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 ofEditFormas the box around the form. You learn it in detail later in this lesson. EditFormneeds a model: a C# object that holds the form's values, likeorder.
InputText and InputTextArea
InputTextis a one-line text box, for a name.InputTextAreais a bigger box with many lines, for a note.- Both work with
stringvalues.
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
InputNumberis a box for numbers, likeintordecimal. It does not accept letters.InputDateshows a date picker. It works withDateTimeorDateOnly.
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
InputCheckboxis a tick box. It works with aboolvalue:truewhen ticked,falsewhen not.
In the below example, InputCheckbox is linked to order.Sugar. The text shows "with sugar" or "no sugar".
InputSelect
InputSelectis 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.
InputRadioGroupholds the group and is linked to the value.- Each
InputRadiois one choice, with its ownValue.
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 onlyValue="Pickup"also works for strings.
InputFile
InputFilelets the user choose a file from their computer, like a photo.- It does not use
@bind-Value. Instead, itsOnChangeevent 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 changename. - Two-way binding shows the value and changes it when the user types:
<input @bind="name" />. @bindworks on plain HTML inputs.@bind-Valueis the same idea for components likeInputText.- By default,
@bindupdates 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 changesnameat 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
@onand 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
@onclickruns 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
@onmouseoverruns when the mouse moves onto an element.@onmouseoutruns when it leaves.@onmousemoveruns as the mouse moves. Its method can takeMouseEventArgs, which has the position, likee.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
@onkeydownruns when a key is pressed in an element, like a text box.- Its method can take
KeyboardEventArgs.e.Keytells 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
@onfocusruns when the user enters a box (clicks or tabs into it).@onblurruns when the user leaves it.@onchangeruns when a value is changed and confirmed, like picking from a list. Its method can takeChangeEventArgs, ande.Valueis 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
EditFormis Blazor's form component. It draws an HTML<form>.Modelis 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-Valueon it, like the built-in ones. - The component needs two parameters:
Value(the value it shows) andValueChanged(anEventCallbackit calls with the new value). @bind-Value="order.Cups"setsValueand listens toValueChangedfor 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. OnSubmiton theEditFormnames the method that runs then.- With validation (checking the values), you use
OnValidSubmitinstead. 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
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
An InputText outside an EditForm | Input components work anywhere | Put input components inside an EditForm | An error: it needs a cascading EditContext |
<input value="@name" /> to read typing | value= is two-way | Use @bind="name" | Typing does not change name |
A normal button inside an EditForm | Buttons only run @onclick | Add type="button" to non-submit buttons | The form submits on every click |
@onclick="Order(tea)" | You can call the method with a value directly | Use a lambda: @onclick="() => Order(tea)" | A build error |
A custom input with only Value | Value is enough for @bind-Value | Add EventCallback<T> ValueChanged | A build error on @bind-Value |
Check Yourself
Exercises
What to Remember
- Input components (
InputText,InputNumber,InputDate,InputCheckbox,InputSelect,InputRadioGroup) go inside anEditFormand use@bind-Value. InputFileusesOnChangeto 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,@onblurand@onchange. Event args likeKeyboardEventArgsgive the details. EditFormtakes aModel. A custom input needsValueandValueChangedfor@bind-Value.OnSubmitruns when the form is submitted.- Reset a form with
order = new();. Give non-submit buttonstype="button".
Next: Form Validation