Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 41 ยท Data Binding and Events

Binding Formats, Events and Modifiers

Fine-tune Blazor data binding with @bind:event for live updates, @bind:format and culture for dates and numbers, @bind:after and @bind:get/@bind:set for side effects, plus debouncing typed input.

Plain @bind covers many cases, but real forms need more. You want a search box that reacts on every keystroke, a date shown in a specific format, a calculation that runs after a value changes, or a setter that normalises the input. Blazor provides binding modifiers for each of these. They all hang off @bind with a colon.

Update on every keystroke: @bind:event

By default a text box updates its field on change (blur or Enter). Switch to input to update continuously:

HTML
<input @bind="query" @bind:event="oninput" />
<p>You typed: @query (@query.Length characters)</p>

@code {
    private string query = "";
}

Now the paragraph follows each keypress. The cost: with Interactive Server, each keystroke is a network message to the server. That is fine for small apps but think twice for expensive handlers.

Dates and numbers: @bind:format and culture

For DateTime and DateOnly you can pick the format shown in the input, and for any parsed type the culture used for converting:

HTML
<input @bind="birthday" @bind:format="yyyy-MM-dd" />

@using System.Globalization
<input @bind="price" @bind:culture="invariantCulture" />

@code {
    private DateTime birthday = new(1990, 5, 17);
    private decimal price = 19.99m;
    private CultureInfo invariantCulture = CultureInfo.InvariantCulture;
}

Notes:

  • @bind:format works for date and time types, not for numbers.
  • type="date" and type="number" inputs already use an invariant ISO-like format in the browser, and Blazor binds them with the invariant culture automatically. You rarely need @bind:culture for them.
  • For a plain text box holding a number, the user's current culture applies (decimal comma versus decimal point). Set the culture deliberately if you parse typed numbers.

Doing something after binding: @bind:after

Often you want to run code whenever a bound value changed, such as refreshing a filtered list. Do not wire @onchange on the same element; use @bind:after:

HTML
<input @bind="filter" @bind:event="oninput" @bind:after="ApplyFilter" />

<ul>
    @foreach (var name in visible)
    {
        <li>@name</li>
    }
</ul>

@code {
    private string filter = "";
    private List<string> all = ["Alice", "Bob", "Carol", "Dave"];
    private List<string> visible = [];

    protected override void OnInitialized() => ApplyFilter();

    private void ApplyFilter() =>
        visible = all.Where(n => n.Contains(filter, StringComparison.OrdinalIgnoreCase)).ToList();
}

@bind:after runs after the field has been updated, and it may return a Task for async work such as a search request.

Full control: @bind:get and @bind:set

.NET 7 added a pair that spells out both directions:

HTML
<input @bind:get="title" @bind:set="SetTitle" @bind:event="oninput" />

@code {
    private string title = "";

    private void SetTitle(string value)
    {
        title = value.Trim().ToUpperInvariant();   // normalise before storing
    }
}

@bind:get reads the value, and @bind:set receives each new value, so you can validate, transform or reject it. @bind:set cannot be combined with @bind:after (do the extra work inside the setter), and a Task-returning setter is allowed.

Why not use a property with a custom setter? You can, and for simple cases that is also fine. @bind:set keeps the logic next to the markup and works with fields and locals.

Debouncing typed input

Searching on every keystroke is wasteful. The usual fix is to wait until the user pauses. A small pattern with a CancellationTokenSource:

C#
private CancellationTokenSource? cts;

private async Task OnSearchChanged()
{
    cts?.Cancel();
    cts = new CancellationTokenSource();
    try
    {
        await Task.Delay(300, cts.Token);
        results = await Api.SearchAsync(query);
    }
    catch (TaskCanceledException) { /* a newer keystroke arrived */ }
}

Use it with @bind="query" @bind:event="oninput" @bind:after="OnSearchChanged".

Runnable stand-in: formats, cultures and debounce

The first part of this stand-in parses user text with two cultures to show why format and culture matter. (A custom NumberFormatInfo represents a decimal-comma culture so the demo runs everywhere.) The second part debounces a burst of keystrokes: only the last one triggers the search.

C# Stand-in: culture-aware parsing and debounce

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.

You will see "1234.56" parse correctly with the dot culture but not as 1234.56 with the comma culture (where the dot is a thousands separator and gives 123456). That is why the browser's number inputs use a fixed invariant format.

Which modifier when?

Need Use
Update on each keystroke @bind:event="oninput"
Specific date format @bind:format="..."
Specific culture @bind:culture="..."
Run code after a change @bind:after="Method"
Transform or validate before storing @bind:get + @bind:set
Wait until typing stops @bind:after + a debounce

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How do you make a bound text box update its field on every keystroke?

    @bind:event selects which DOM event triggers the update; oninput fires on every change of the text.
  2. 2. Which modifier runs a method after the bound field has been updated?

    @bind:after runs once the value has been stored, and may return a Task.
  3. 3. What are @bind:get and @bind:set for?

    They let you spell out both directions of the binding with your own code.
  4. 4. Why debounce a search box bound to oninput?

    Waiting for a pause reduces needless work and server round trips.

Summary

  • @bind:event="oninput" updates on every keystroke; the default is change.
  • @bind:format and @bind:culture control date formatting and number parsing.
  • @bind:after runs code after a change; @bind:get/@bind:set intercept the new value.
  • Debounce frequent updates before calling expensive operations.

Next: Event Callbacks and Component Communication