Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 41 ยท Data Binding and Events

Two-Way Data Binding with @bind

Learn Blazor two-way data binding with @bind for text boxes, checkboxes, selects and radio buttons, what it expands to (value plus onchange), and how to bind to properties and component parameters.

One-way binding shows a value; two-way binding also writes changes back. Type in a text box and a C# field changes; change the field in code and the text box updates. In Blazor this is the @bind directive, and it is the glue that makes forms feel effortless. Under the hood it is only a pair of simple things you already know: an attribute for the value and an event handler.

The simplest case

HTML
<input @bind="name" />
<p>Hello, @name!</p>

@code {
    private string name = "Ada";
}

The input starts with "Ada". When the user edits the text and leaves the box (the change event fires on blur or Enter), name gets the new value, the component re-renders, and the paragraph updates.

What @bind expands to

@bind="name" is shorthand for these two attributes:

HTML
<input value="@name" @onchange="@(e => name = (string?)e.Value)" />

So the element's value is set from the field, and the change event sets the field from the element. That is the whole trick. Knowing it explains most binding behaviour, including formats, events and how to bind your own components.

Binding to other input types

@bind works for the common form controls and converts text to the field's type:

HTML
<input type="number" @bind="quantity" />          @* int *@
<input type="checkbox" @bind="subscribed" />      @* bool *@
<input type="date" @bind="dueDate" />             @* DateTime *@
<textarea @bind="notes"></textarea>               @* string *@

<select @bind="color">
    <option value="red">Red</option>
    <option value="green">Green</option>
    <option value="blue">Blue</option>
</select>

@code {
    private int quantity = 1;
    private bool subscribed;
    private DateTime dueDate = DateTime.Today;
    private string notes = "";
    private string color = "green";
}

Checkboxes bind to bool through checked. Selects bind to the selected option's value; the field can also be an enum or int when option values match. Conversion failures, such as a number box that is cleared, revert to the previous value instead of crashing.

Binding to properties and models

Anything assignable works, including properties of objects:

HTML
<input @bind="person.FirstName" />
<input @bind="person.Age" />

@code {
    private Person person = new() { FirstName = "Grace", Age = 36 };

    private class Person
    {
        public string FirstName { get; set; } = "";
        public int Age { get; set; }
    }
}

@bind needs something it can assign to: a field, a property with a setter, or an indexer. It cannot bind to a method result or a read-only value.

Radio buttons

Radio groups need a little more because several inputs share one field. The built-in InputRadioGroup component (see the Forms chapter) handles it; without it, bind each radio with checked and @onchange:

HTML
@foreach (var size in new[] { "Small", "Medium", "Large" })
{
    <label>
        <input type="radio" name="size" value="@size"
               checked="@(selected == size)"
               @onchange="() => selected = size" />
        @size
    </label>
}

Binding to your own component

Two-way binding between components uses a parameter plus a matching callback named Changed. A child exposing both can be bound with @bind-Value:

HTML
@* Components/Stepper.razor *@
<button @onclick="() => Change(-1)">-</button>
<span>@Value</span>
<button @onclick="() => Change(+1)">+</button>

@code {
    [Parameter] public int Value { get; set; }
    [Parameter] public EventCallback<int> ValueChanged { get; set; }

    private Task Change(int by) => ValueChanged.InvokeAsync(Value + by);
}
HTML
<Stepper @bind-Value="quantity" />
<p>Quantity: @quantity</p>

@bind-Value="quantity" expands to Value="@quantity" plus ValueChanged="@(v => quantity = v)". Notice the child never assigns to Value itself; it asks the parent to change it, following the rule from Component Parameters. Event Callbacks go deeper.

Runnable stand-in: two-way binding from scratch

This stand-in models a binding as a getter and a setter. Bind produces a "control" whose displayed value follows the field and whose edits flow back, including text-to-type parsing that rejects bad input just like a number box.

C# Stand-in: a binding is a getter plus a setter

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.

The same two functions, "read the field" and "write the field", are all that @bind generates for each control.

Common mistakes

  • Binding to a read-only expression such as @bind="items.Count" (no setter).
  • Expecting live updates while typing. The default event is change, which fires on blur. Use @bind:event="oninput", shown in Binding Formats and Modifiers.
  • Mixing @bind and @onchange on the same element; both claim the same event.
  • Assuming @bind validates. It only converts; validation belongs to forms (EditForm Basics).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does <input @bind="name" /> expand to?

    @bind sets value from the field and updates the field in the change event.
  2. 2. When does @bind on a text box update the field by default?

    The default event is change; use @bind:event="oninput" for live updates.
  3. 3. To use @bind-Value on your own component you need a Value parameter and...

    The convention is Value plus ValueChanged; @bind-Value wires both.
  4. 4. Which cannot be the target of @bind?

    Binding needs something assignable.

Summary

  • @bind is shorthand for a value attribute plus a change handler that writes back.
  • It works with text, numbers, dates, checkboxes, selects and properties of objects.
  • Custom components bind with a Value parameter and a ValueChanged callback via @bind-Value.
  • Defaults to the change event; there are modifiers for other events and formats.

Next: Binding Formats and Modifiers