overview
HTML events, like onclick
, can be handled in Blazor. To specify an event callback, use an attribute that starts with @on
and ends with the event name. The value of the attribute (IncrementCount
) is the name of the C# method (event handler) to call:
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
Event handlers can also be defined inline using C# lambda expressions:
<button class="btn btn-primary" @onclick="() => currentCount++">Click me</button>
Event handler methods can optionally take an event argument with information about the event:
<input @onchange="InputChanged" />
<p>@message</p>
@code {
string message = "";
void InputChanged(ChangeEventArgs e)
{
message = (string)e.Value;
}
}
default event arguments
Some events support event arguments. For example:
@onclick
passesMouseEventArgs
@onkeydown
passesKeyboardEventArgs
Example
<button @onclick="ShowLocation">Show</button>
@code
{
private void ShowLocation(MouseEventArgs e)
{
}
}
EventCallback
When an event occurs in a child Component, use EventCallback
to trigger code to execute in the parent Component:
ChildComponent.razor
<button @onclick="TriggerCallbackToParent">Show</button>
@code
{
[Parameter]
public EventCallback<MouseEventArgs> TriggerCallbackToParent { get; set; }
}
ParentComponent.razor
<ChildComponent TriggerCallbackToParent="ShowPopup"></ChildComponent>
@code
{
private void ShowPopup()
{
…
}
}