...

/

Event Handling in Razor Components

Event Handling in Razor Components

Learn event handling in Razor components.

Anyone familiar with front-end web development would be familiar with document object model (DOM) events, such as click, change, copy, paste, etc. Blazor supports all these events, but instead of calling a JavaScript function when such an event gets triggered, Blazor will trigger a C# method.

Press + to interact
Event handling diagram
Event handling diagram

In this lesson, we will look at various ways to handle Blazor events. We will be using the code in the following project setup:

using Microsoft.AspNetCore.Components;

namespace Blazor;

[EventHandler("onspecialpaste", typeof(SpecialPasteEventArgs),
    enableStopPropagation: true, enablePreventDefault: true)]
public static class EventHandlers
{
}

public class SpecialPasteEventArgs : EventArgs
{
    public string? PastedData { get; set; }
}
Project setup to demonstrate Razor component event handling

In this project, we have some examples of basic event handling in Razor components. We've we also added an example of custom event handling.

Basic event handling

The most basic way of handling a Blazor event is to attach a specific C# method to a specific DOM event. We have an example of it in the Counter.razor file that is included in the standard Blazor project templates for both Blazor WebAssembly and Blazor Server.

Blazor events always start with the @ character. Then, we specify any of the standard DOM events with on prepended at the beginning (onclick, onchange, oncopy, onpaste, etc). Then, we put the equality sign and put the name of the method that we want to be triggered by this event.

If we open this file in the above project, we will see that on line 9 the IncrementCount method is attached to the @onclick event in a button element. The IncrementCount method is defined on line 14. This method is triggered when the user clicks the button.

Blazor event arguments

Attaching methods without parameters to DOM events is not the only way to trigger the events. We can also capture event arguments as the method ...