@on<event>

React to HTML events. HTML events are "things" that happen to HTML elements. When @on<event> is used, Blazor Server can "react" on these events.

There are 2 ways to create an event handler for an element, with or without a delegate.


Event handler without delegate

Without a delegate, you will not be able to pass the event argument or parameter to the event handler but the syntax is simpler.

For example, if you want to handle the click event, you can use the @onclick directive and assign it to a method without any param.

@inject IJSRuntime JSRuntime

<button @onclick="OnClick">Click me</button>

@code {
    private async void OnClick()
    {
        await JSRuntime.InvokeVoidAsync("alert","Blazor School https://blazorschool.com");
    }
}

Event handler with a delegate

With a delegate, you will be able to get the event argument and can pass parameters to the event handler.

Get the event argument

To get the event argument, you just need to create a lambda with one argument and pass it to the event handler.

For example, if you want to handle the oninput event, you can use the @oninput directive as follows:

<input @oninput="(e) => OnInput(e)" />

@code {
    private void OnInput(ChangeEventArgs eventArgs)
    {
        LastKey = eventArgs.Value.ToString().LastOrDefault();
    }
}

Every @on<event> directive has different arguments. You will have a better look for each event later on. In this example, the @oninput uses ChangeEventArgs as the event argument.

Pass parameters to the event handler

To pass the parameter to the event handler, you will also need to create a lambda and pass the parameter to the event handler.

For example, if you want to handle the onkeydown event, you can use the @onkeydown directive as follows:

<input @onkeydown="() => OnKeyDown(Random.Next(0,100))" />
<span>Custom Parameter: @CustomParameter</span>

@code {
    private int CustomParameter;
    private Random Random = new();

    private void OnKeyDown(int parameter)
    {
        CustomParameter = parameter;
    }
}
BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2025 Blazor School
An unhandled error has occurred. Reload 🗙