Event Handling in Blazor
This tutorial covers how to handle user interactions and other events within your Blazor applications.
Blazor allows you to easily handle HTML DOM events directly in your C# code. This is a fundamental aspect of creating interactive web applications. Blazor's event handling mechanism is designed to be intuitive and efficient.
Basic Event Handling
To handle an event, you use the @on*
syntax. For example, to handle a button's click event, you would use @onclick
.
Example: A Simple Counter
Let's create a component with a button that increments a counter when clicked.
@page "/event-handling-example"
<h3>Counter</h3>
<p>Current count: @currentCount</p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
@code {
private int currentCount = 0;
private void IncrementCount()
{
currentCount++;
}
}
In this example:
@page "/event-handling-example"
defines the route for this component.@currentCount
displays the current value of the counter.@onclick="IncrementCount"
binds the button's click event to theIncrementCount
method defined in the@code
block.- The
IncrementCount
method simply increments thecurrentCount
variable. Blazor automatically re-renders the component when the state changes.
Handling Different Event Types
Blazor supports a wide range of standard HTML DOM events. Here are a few common examples:
@onchange
: For input elements when their value changes.@onmouseover
: When the mouse pointer moves over an element.@onkeydown
: When a key is pressed down.@onfocus
: When an element receives focus.@onblur
: When an element loses focus.
Example: Input Change Detection
This example shows how to capture the value of an input field as it changes.
<input type="text" @onchange="HandleInputChange" placeholder="Type something..." />
<p>Last typed value: @lastInputValue</p>
@code {
private string lastInputValue = "";
private void HandleInputChange(ChangeEventArgs e)
{
lastInputValue = e.Value?.ToString() ?? "";
}
}
The ChangeEventArgs
object provides information about the event, including the new value of the input element.
Event Modifiers
Blazor provides powerful event modifiers to control event behavior, such as preventing default actions or stopping event propagation.
Common Event Modifiers:
prevent-default
(or.preventDefault
): Prevents the browser's default action for the event (e.g., preventing a form submission).stop-propagation
(or.stopPropagation
): Stops the event from bubbling up the DOM tree.capture
(or.capture
): Triggers the event handler during the capture phase instead of the bubbling phase.once
(or.once
): The event handler will only be triggered once.
Example: Form Submission with Prevention
This example demonstrates how to prevent the default form submission behavior and handle it with Blazor.
<EditForm OnValidSubmit="HandleValidSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<div>
<label for="name">Name:</label>
<InputText id="name" @bind-Value="userName" />
</div>
<button type="submit" class="btn btn-success">Submit</button>
</EditForm>
<p>Submitted Name: @submittedName</p>
@code {
private string userName;
private string submittedName;
private void HandleValidSubmit()
{
submittedName = userName;
// In a real app, you'd do something with the data here, like saving it.
Console.WriteLine($"Form submitted with name: {userName}");
}
}
Using <EditForm>
with OnValidSubmit
is the recommended Blazor way for form handling, as it inherently manages validation and submission prevention. For non-form elements or more direct control, you can use @onsubmit.prevent-default
.
Event Callback Parameters
Many events pass specific data to the event handler through EventArgs objects. You can access this data to perform more complex logic.
Common EventArgs Types:
MouseEventArgs
: For mouse events (e.g.,clientX
,clientY
).KeyboardEventArgs
: For keyboard events (e.g.,Key
,Code
,CtrlKey
).ChangeEventArgs
: For input elements.DragEventArgs
: For drag-and-drop events.
Example: Mouse Position on Click
This component will display the coordinates of where the user clicked.
<div style="width: 200px; height: 100px; background-color: #eee; border: 1px solid #ccc; text-align: center; line-height: 100px;"
@onclick="HandleDivClick">
Click me to get coordinates
</div>
<p>Mouse Clicked at: X=@mousePosition.X, Y=@mousePosition.Y</p>
@code {
private MouseEventArgs mousePosition;
private void HandleDivClick(MouseEventArgs e)
{
mousePosition = e;
}
}
Event Callback Delegates (EventCallback
)
For component development, EventCallback
and EventCallback<T>
are crucial. They allow parent components to subscribe to events raised by child components.
ChildComponent.razor
<button @onclick="NotifyParent">Trigger Event</button>
@code {
[Parameter]
public EventCallback OnSomethingHappened { get; set; }
private void NotifyParent()
{
OnSomethingHappened.InvokeAsync();
}
}
ParentComponent.razor
<ChildComponent OnSomethingHappened="@HandleChildEvent" />
<p>Child event received: @childEventMessage</p>
@code {
private string childEventMessage = "Waiting for event...";
private void HandleChildEvent()
{
childEventMessage = "Event received from child!";
}
}
EventCallback<T>
is used when the event needs to pass a specific type of data, for example, EventCallback<MouseEventArgs>
.
Handling Multiple Events
You can attach multiple event handlers to a single element.
<button @onclick="HandleClick" @onmouseover="HandleMouseOver">Hover and Click</button>
@code {
private void HandleClick() { Console.WriteLine("Clicked!"); }
private void HandleMouseOver() { Console.WriteLine("Mouse over!"); }
}
Conclusion
Blazor's event handling system is a powerful tool that simplifies the process of making your web applications interactive. By leveraging @on*
syntax, event modifiers, and EventCallback
, you can efficiently respond to user actions and build dynamic user interfaces.
Pro Tip:
For complex scenarios or when you need fine-grained control over event data, explore the various EventArgs
types available in Blazor.
Continue to the next section on Forms and Validation to learn how to handle user input and data validation.