Event Handling
Learn how to handle click events in Blazor WebAssembly.
We'll cover the following...
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:
<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:
<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:
ClipboardEventArgs
DragEventArgs
ErrorEventArgs
EventArgs
FocusEventArgs
MouseEventArgs
PointerEventArgs
WheelEventArgs
ProgressEventArgs
TouchEventArgs