Razor Component DOM Event Handling

DOM events are generated as a result of actions taken by a user in the course of interacting with a browser-based application. Actions that generate DOM events include clicking on a button, changing the value of a form input or pressing a key on a keyboard. DOM events in a Blazor application can be handled in the traditional way via JavaScript, or they can be handled using C# code.

Blazor enables you to wire up listeners, or event handlers for these events so that you can execute logic written in C# code in response to user actions.

Blazor event handlers are assigned to an attribute in the Razor component in which the event takes place. These event handlers are named the same as JavaScript event handlers. A click event handler for example is named onclick, and a change event handler is named onchange. What differentiates a Blazor event handler from a JavaScript event handler is that the Blazor version is prefixed with the Razor @ symbol:

<button @onclick=...>Click me</button>

The code to be executed is provided to the event handler as the attribute's value. In the following example, the code to be executed is represented as a lambda expression that has been applied to the onclick event handler. It sets the value of the message field when the button is clicked:

<button @onclick=@(() => message = "Message set by lambda")>Click</button> 

<p>@message</p>

@code {
    string message { get; set; }
}

Alternatively, the value provided to the event handler can be the name of a method that should execute in response to the event. The next example shows how this works with the SetMessage method, specified in the @code block:

<button @onclick=SetMessage>Click</button> 

<p>@message</p>

@code {
    string message { get; set; }
    
    void SetMessage()
    {
        message = "Message set in method";
    }
}

The handler is created as an EventCallback<T> by the EventCallback.Factory.Create method in Blazor. You can see this in the code that is generated for the BuildRenderTree method of the component.

protected override void BuildRenderTree(RenderTree __builder)
{
    __builder.OpenElement(0, "button");
    __builder.AddAttribute<MouseEventArgs>(1, "onclick", EventCallback.Factory.Create<MouseEventArgs>(this, new Action(this, EventDemo.SetMessage)
}

You don't need quotes around the attribute value, but you can provide them. The EventCallback will work just the same:

<button @onclick="@(() => message = "Message set by lambda")">Click</button> 

<p>@message</p>

@code {
    string message { get; set; }
}

EventArgs

The EventCallback.Factory.Create (which features in the generated code earlier) is a generic method that has an EventArgs type parameter. EventArgs holds information about the event that was raised. The actual EventArgs type and the data that it provides will depend on the event. For example, the type of EventArgs mapped to the onclick event is MouseEventArgs.

Supported EventArgs, along with some general events are:

  • Clipboard
  • Drag
  • Error
  • Focus
  • Keyboard
  • Mouse
  • Pointer
  • Progress
  • Touch
  • Wheel

The EventArgs parameter is passed to the method in the lambda expression below, and used to log the coordinates of the click to the browser console:

<button @onclick=@((e) => Log(e))>Event Args Demo</button>

@code {
    void Log(MouseEventArgs e)
    {
        Console.WriteLine($"Click Coordinates: {{x: {e.ClientX}, y: {e.ClientY}}}");
    }
}

EventCallback Parameters

Sometimes, you might want to allow the parent component to specify the logic to be executed in response to an event raised in a child component. A component parameter typed as an EventCallback provides a mechanism for parent components to hook into events raised within the child component. The following example illustrates a simple component with a button:

<div style="border:1px solid #eee;padding:10px;">
    <h3>Child Component</h3>
    <button @onclick=ClickCallback>ChildComponent Button</button>
</div>
@code {
    [Parameter]
    public EventCallback ClickCallback { get; set; }
}

The component also has an EventCallback parameter named ClickCallback which has been assigned to the @onclick event of the button. This enables parents to subscribe to this component's click event when it is used as a child, and execute code defined in the parent:

<ChildComponent ClickCallback=ShowMessage />

<p>@message</p>
@code{
    string message { get; set; }

    public void ShowMessage()
    {
        message = "Child button was clicked";
    }
}

In this example, the parent component has assigned its own ShowMessage method to the child component's ClickCallback parameter, resulting in its message field being assigned when the child component's button is clicked:

Blazor EventCallback

Last updated: 15/02/2023 08:59:36

Latest Updates

© 2023 - 2024 - Mike Brind.
All rights reserved.
Contact me at Outlook.com