Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 41 ยท Data Binding and Events

Event Handling in Blazor

Handle user events in Blazor with @onclick, @oninput, @onkeydown and @onsubmit: event argument types, lambda handlers, async handlers, preventDefault, stopPropagation and common event pitfalls.

Interactive UI means reacting to what people do: clicks, typing, key presses, form submits, mouse movement. In Blazor you attach a C# method to a DOM event with an attribute that starts with @on. The browser raises the event, Blazor calls your method, and then the component renders again. No JavaScript is involved in the handler.

The basics

HTML
<button @onclick="Save">Save</button>
<input @oninput="OnTyping" />
<select @onchange="OnPick">...</select>

@code {
    private void Save() { /* ... */ }
    private void OnTyping(ChangeEventArgs e) => Console.WriteLine(e.Value);
    private void OnPick(ChangeEventArgs e) => Console.WriteLine(e.Value);
}

The attribute name is @on plus the DOM event name: @onclick, @ondblclick, @onmouseover, @onkeydown, @onfocus, @onblur, @onchange, @oninput, @onsubmit, @onscroll, and many more. The value is a method name, a lambda, or a delegate.

Event arguments

A handler may take no parameters or one parameter of the matching event args type, which carries details about the event:

Event Args type Useful members
@onclick, @onmousemove MouseEventArgs ClientX, ClientY, Button, ShiftKey, CtrlKey
@onkeydown, @onkeyup KeyboardEventArgs Key, Code, ShiftKey, Repeat
@oninput, @onchange ChangeEventArgs Value (an object?)
@onfocus, @onblur FocusEventArgs Type
@ondrop and drag events DragEventArgs DataTransfer
@onsubmit EventArgs (forms are covered in the Forms chapter)
HTML
<input @onkeydown="HandleKey" placeholder="Press Enter" />

@code {
    private void HandleKey(KeyboardEventArgs e)
    {
        if (e.Key == "Enter")
        {
            Console.WriteLine("Submitted");
        }
    }
}

Lambdas and passing arguments

To pass your own data to a handler, use a lambda:

HTML
@foreach (var item in items)
{
    <button @onclick="() => Select(item)">@item.Name</button>
}

<button @onclick="@(e => Move(e.ShiftKey ? 10 : 1))">Move</button>

In foreach loops this captures the right item. With a for loop, copy the index first, as in Conditionals and Loops.

Async handlers

Handlers can be async. Blazor renders when the handler starts awaiting and again when it completes:

HTML
<button @onclick="LoadAsync" disabled="@busy">@(busy ? "Loading..." : "Load")</button>

@code {
    private bool busy;
    private string? result;

    private async Task LoadAsync()
    {
        busy = true;                          // rendered while awaiting
        result = await Http.GetStringAsync("/api/data");
        busy = false;                         // rendered when complete
    }
}

Return Task, never async void: with async void, exceptions escape and the framework cannot tell when you finished. Disabling the button while busy prevents double submits.

preventDefault and stopPropagation

Some events have default browser behaviour: a link navigates, a form submits, a key adds text. You can cancel it per element:

HTML
<a href="/somewhere" @onclick="Track" @onclick:preventDefault>Tracked link</a>

<div @onclick="OuterClick">
    <button @onclick="InnerClick" @onclick:stopPropagation>Inner</button>
</div>

@onclick:preventDefault stops the browser's default action; @onclick:stopPropagation keeps the event from bubbling to parent elements. You can also bind them to a boolean: @onkeydown:preventDefault="shouldBlock".

Because of how Blazor Server and WebAssembly work, the decision to cancel must be made in the browser before your C# runs, which is why these are attributes and not something you do inside the handler.

Event handlers and rendering

After a handler finishes, the component re-renders automatically. Two consequences:

  • Don't call StateHasChanged() in a normal handler. It is already done for you.
  • Frequent events can be expensive. @onmousemove and @oninput fire a lot. With Interactive Server each event is a network message, so debounce, or use @onchange (fires when the control loses focus) when you do not need every keystroke.

Runnable stand-in: an event dispatcher

Here is a simplified browser-to-C# event pipe. Events carry an args object; a registry maps (element, eventName) to a handler; the dispatcher honours a PreventDefault flag decided before calling the handler, then triggers a re-render. All names are invented for the demonstration.

C# Stand-in: dispatching events to handlers

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.

Notice that each handled event ends with a render, but the unhandled one does not.

Common mistakes

  • Writing @onclick="Save()". That calls Save while rendering. Pass the method name Save or a lambda () => Save().
  • Using async void. Return Task.
  • Expecting e.Value to be typed. It is object?; convert it, or use binding instead of manual @oninput handling.
  • Doing slow synchronous work in a handler. It blocks the UI thread (and on Blazor Server, other work on the circuit).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type of argument does an @onkeydown handler receive?

    KeyboardEventArgs carries Key, Code and modifier flags.
  2. 2. What is wrong with <button @onclick="Save()">?

    A delegate is expected, not the result of calling the method.
  3. 3. How do you stop a link from navigating when clicked?

    The preventDefault directive attribute is applied in the browser before your handler runs.
  4. 4. Should an async handler return void or Task?

    Task lets the framework observe completion and exceptions; async void does not.

Summary

  • @onclick, @oninput, @onkeydown and other @on... attributes bind events to C# methods or lambdas.
  • Handlers can take an event args object such as MouseEventArgs, KeyboardEventArgs or ChangeEventArgs.
  • Use lambdas to pass data, async Task handlers for slow work, and :preventDefault / :stopPropagation to control the browser.
  • Components re-render automatically after a handler finishes.

Next: Two-Way Data Binding