Event Handling

Learn how to handle click events in Blazor WebAssembly.

Razor components handle events by using an HTML element attribute named @on{EVENT} where EVENT is the name of the event.

The following code calls the OnClickHandler method when the button is clicked:

Press + to interact
<button class="btn btn-success" @onclick="OnClickHandler">
Click Me
</button>
@code {
private void OnClickHandler()
{
// ...
}
}

Since event handlers automatically trigger a UI render, we do not need to call StateHasChanged when processing them. Event handlers can be used to call both synchronous and asynchronous methods. Also, they can reference any arguments that are associated with the event.

The following code asynchronously calls the OnChangeHandler method when the checkbox is changed:

Press + to interact
<input type="checkbox" @onchange="OnChangedHandler" />
@code {
private async Task OnChangedHandler(ChangeEventArgs e)
{
newvalue = e.Value.ToString();
// await ...
}
}

In the preceding code, the ChangeEventArgs class is used to supply information about the change event. The event arguments are optional and should only be included if they are used by the method.

All of the EventArgs classes that are supported by the ASP.NET Core framework are supported by the Blazor WebAssembly framework. This is a list of the supported EventArgs classes:

  1. ClipboardEventArgs
  2. DragEventArgs
  3. ErrorEventArgs
  4. EventArgs
  5. FocusEventArgs
...
  1. MouseEventArgs
  2. PointerEventArgs
  3. WheelEventArgs
  4. ProgressEventArgs
  5. TouchEventArgs
...