Handling Events in Blazor
Blazor allows you to handle user interactions and browser events directly within your C# code. This simplifies event handling compared to traditional JavaScript-heavy approaches.
Event Attributes
Blazor uses familiar HTML event attributes, prefixed with an `@`. When an event occurs on an HTML element, Blazor captures the event and invokes the specified C# method.
Example: Button Click
To handle a button click, you can use the @onclick
attribute:
<button @onclick="HandleClick">Click Me</button>
@code {
private void HandleClick()
{
// Your logic here
Console.WriteLine("Button was clicked!");
}
}
Event Parameter Types
Many Blazor event handlers automatically receive an appropriate event parameter object. For example, @onclick
handlers can accept an MouseEventArgs
object.
Example: Mouse Event Arguments
<button @onclick="HandleMouseClick">Hover Over Me</button>
@code {
private void HandleMouseClick(MouseEventArgs e)
{
Console.WriteLine($"Mouse clicked at coordinates: X={e.ClientX}, Y={e.ClientY}");
}
}
Common event argument types include:
MouseEventArgs
for mouse events (click, mouseover, etc.)KeyboardEventArgs
for keyboard events (keydown, keypress, keyup)EventArgs
for simpler events that don't require specific data.
Event Bubbling
By default, Blazor events bubble up the DOM tree. If you don't want an event to bubble further, you can use the @on*
attribute with stopPropagation
.
Example: Stopping Event Propagation
<div @onclick="HandleOuterClick">
Outer Element
<button @onclick:stopPropagation="true" @onclick="HandleInnerClick">
Inner Button
</button>
</div>
@code {
private void HandleOuterClick()
{
Console.WriteLine("Outer element clicked.");
}
private void HandleInnerClick()
{
Console.WriteLine("Inner button clicked. Event propagation stopped.");
}
}
Preventing Default Behavior
Sometimes you need to prevent the browser's default action for an event (e.g., preventing form submission on button click). You can use preventDefault
for this.
Example: Preventing Default Form Submission
<EditForm OnValidSubmit="HandleFormSubmit">
<DataAnnotationsValidator />
<ValidationSummary />
<InputText @bind-Value="model.Name" />
<button type="submit">Save</button>
</EditForm>
@code {
// ... model definition ...
// private MyModel model = new MyModel();
private void HandleFormSubmit()
{
// This method will be called after validation.
// The default form submission is already prevented by EditForm.
Console.WriteLine("Form submitted successfully!");
}
}
For form submissions specifically, using the EditForm
component and its OnValidSubmit
event is the recommended Blazor way, as it handles validation and submission logic more robustly. The @onclick:preventDefault
is more generally applicable to other HTML elements.
Event Modifiers
Blazor provides several event modifiers to control event behavior:
@on*
: The standard event handler.@on*:stopPropagation
: Stops the event from bubbling up.@on*:preventDefault
: Prevents the browser's default action for the event.@on*:stopImmediatePropagation
: Stops the event from propagating further and prevents other listeners on the same element from being invoked.@on*:once
: Ensures the event handler is executed only once.
Example: Combining Modifiers
<a href="https://example.com" @onclick:preventDefault @onclick:stopPropagation="true" @onclick="HandleLinkClick">
Visit Example.com (No Default, No Bubble)
</a>
@code {
private void HandleLinkClick(MouseEventArgs e)
{
Console.WriteLine("Link clicked, but default navigation prevented and event stopped from bubbling.");
// You can navigate programmatically here if needed.
}
}
Custom Events
While Blazor excels at handling standard DOM events, you can also define and dispatch custom JavaScript events that Blazor can listen to. This is typically achieved via JavaScript interop.
Event Handling in Components
Components can define their own events using EventCallback
. Child components can notify parent components of events occurring within them.
Example: Child Component Event
<!-- ParentComponent.razor -->
<ChildComponent OnMyCustomEvent="HandleCustomEvent" />
@code {
private void HandleCustomEvent(string message)
{
Console.WriteLine($"Received custom event: {message}");
}
}
<!-- ChildComponent.razor -->
<button @onclick="TriggerCustomEvent">Trigger Event</button>
@code {
[Parameter]
public EventCallback<string> OnMyCustomEvent { get; set; }
private void TriggerCustomEvent()
{
OnMyCustomEvent.InvokeAsync("Hello from Child!");
}
}