Basic Event Handling in Blazor

Categories : ASP.NET Core

Author : Golda G Date : Mar 1, 2022

Basic Event Handling in Blazor

This article is to explain how event handling works in Blazor. The @on{event} attribute in Razor is the event handling attribute. The {event} may be any event. For example, For button @onclick is a click event. In checkbox @onchange is a change event it will trigger, when checking or unchecking the checkbox.

The following is an example for @onclick. In this code, the @page directive is added for routing. Then @result property value is added to display the result. Then the @onclick attribute is added to the button and the DisplayMessage method is assigned to it. When the user clicks the button it will display the message.

@page “/”

<div>@result</div>

<br />
<button @onclick=”DisplayMessage”>Click Here</button>

@code
{
    public string result { get; set; }

    void DisplayMessage()
    {
        result = “The button is clicked”;
    }
}

The following is an output of the above code.

Event Handling

Lambda Expressions

You can achieve the same result as above using lambda expressions.

@page “/”

<div>@result</div>

<br />
<button @onclick=”@(e=>DisplayMessage())”>Click Here</button>

@code
{
    public string result { get; set; }

    void DisplayMessage()
    {
        result = “The button is clicked”;
    }
}

Also, you can pass arguments to the @onclick method using the Lambda expression.

The following code explains how to pass arguments. Here in GetSum() method two arguments a and b are passed.

@page “/”

Sum of 1 + 2 = <strong>@result</strong>

<br /><br />
<button @onclick=”@(e=>GetSum(1, 2))”>Sum</button>

@code
{
    public int? result { get; set; }

    void GetSum(int a, int b)
    {
        result = 1 + 2;
    }
}

The following is an output of the above code.

Event Handling

This article explains what is event handling in Blazor and how to pass parameters to an event handler.

If you have questions, please leave your comments.

Comments are closed.

×