Blazor Event Handling

Blazor allows you to handle browser events directly within your C# code. This enables rich, interactive user interfaces without writing JavaScript for many common scenarios. Event handling in Blazor is declarative and intuitive, seamlessly integrating with your component logic.

Understanding Event Binding

Event binding in Blazor uses a special syntax to connect an HTML element's event to a C# method in your component. The syntax is `on[eventname]="MethodName"`.

Example: Handling a Button Click

Let's bind the `onclick` event of a button to a C# method named IncrementCount.

Current count: 0


<p>Current count: <strong>@currentCount</strong></p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private void IncrementCount()
    {
        currentCount++;
    }
}
                

When the button is clicked, the IncrementCount method is executed, which increments the currentCount variable. Blazor then automatically re-renders the component to reflect the updated value.

Event Arguments

Many browser events carry data related to the event. Blazor provides strongly-typed event arguments for these events, allowing you to access this data directly in your C# handler.

Example: Handling Input Events

For input elements like <input>, you can bind to events like oninput or onchange and access the event arguments.

You typed:


<label for="nameInput">Enter your name:</label>
<input type="text" id="nameInput" @oninput="HandleInput" placeholder="Type here...">
<p>You typed: <strong>@typedText</strong></p>

@code {
    private string typedText = string.Empty;

    private void HandleInput(ChangeEventArgs e)
    {
        typedText = e.Value.ToString();
    }
}
                

The ChangeEventArgs object contains a Value property which holds the current value of the input element.

Event Modifiers

Blazor offers event modifiers to simplify common event handling tasks, such as preventing default browser behavior or stopping event propagation.

Common Event Modifiers:

Example: Preventing Default Form Submission

This example shows how to prevent the default form submission behavior and handle it with C#.

Form submitted via Blazor!


<form @onsubmit="HandleFormSubmit">
    <input type="text" placeholder="Enter something...">
    <button type="submit" class="btn btn-secondary">Submit</button>
</form>
<p>Form submitted via Blazor!</p>

@code {
    private void HandleFormSubmit()
    {
        // Custom form submission logic here
        Console.WriteLine("Form submitted via Blazor event handler.");
        // The default form submission is prevented by the @onsubmit binding.
    }
}
                

By simply using @onsubmit="HandleFormSubmit" on the <form> element, Blazor automatically prevents the default browser form submission. If you needed to explicitly prevent it for some reason (e.g., with an explicit event object), you could use @onsubmit.prevent-default="HandleFormSubmit".

Event Callback Delegate

For creating reusable components, you can use the EventCallback delegate. This allows child components to raise events that parent components can subscribe to.

EventCallback is strongly recommended over Action or Func for event handling in reusable Blazor components. It handles asynchronous operations and binding correctly.

Example: Custom Button Component with EventCallback

A custom button that notifies its parent when clicked.

Custom button clicked: false


// --- ParentComponent.razor ---
<CustomButton OnClick="HandleCustomButtonClick" Text="My Custom Button"></CustomButton>
<p>Custom button clicked: <strong>@customButtonClicked</strong></p>

@code {
    private bool customButtonClicked = false;

    private void HandleCustomButtonClick()
    {
        customButtonClicked = true;
    }
}

// --- CustomButton.razor (Child Component) ---
<button class="btn btn-outline-primary" @onclick="NotifyParent">@Text</button>

@code {
    [Parameter]
    public string Text { get; set; }

    [Parameter]
    public EventCallback OnClick { get; set; }

    private void NotifyParent()
    {
        OnClick.InvokeAsync();
    }
}
                

In this example, the CustomButton component exposes an OnClick parameter of type EventCallback. When the internal button is clicked, NotifyParent is called, which invokes the EventCallback asynchronously. The parent component receives this notification and updates its state.

Binding to Different Event Types

Blazor supports binding to a wide range of standard HTML events, including but not limited to:

For custom HTML elements or third-party JavaScript libraries, you can also create custom event bindings or use JavaScript interop to dispatch events that Blazor components can listen to.

When binding to events that pass complex data (like mouse events), Blazor automatically provides specialized argument types (e.g., MouseEventArgs, KeyboardEventArgs) for your handler methods.