Using the button click event in Blazor WebAssembly is extremely important for sending data, among other things.
This article explains how to implement the button onclick event in a Blazor Wasm app. We demonstrate how to set up a Blazor call onclick method and bind it to an HTML element.
There are some simple bugs that can cause Blazor onclick not to work. This article highlights some of the more common errors that can occur.
We also demonstrate how to use the parameter attribute to invoke a button event when another Razor component is clicked.
Then we'll see how other HTML events are implemented in Blazor.
Finally, we'll show how to set up a Blazor asynchronous event handler, which is very important when your app makes API calls.
Using a sample Blazor WebAssembly notes
We've created a simple Blazor WebAssembly notes app to demonstrate our examples.
we start with onesupervision
Model. HEsupervision
The model is responsible for storing the actual note and the date/time it was created.
// Note.cspublic class Note{public string Message { get; } public DateTimeOffset Created { erhalten; }public Note(chain message){Message = message;Created = DateTimeOffset.UtcNow;}}
From there we have two Razor components. The first isNoteViewComponent.razor
and shows the current note. TOsupervision
type is passed as a parameter to the Razor component to indicate which note it refers to.
<!-- NoteViewComponent.razor -->@if (Note != null){ <li> <span>@Note.Message</span> <span>Created: @Note.Created.ToUniversalTime().ToString(" ddd d MMM aaaa HH:mm:ss")</span> </li>}@code { [Parameter] public Note Note { get; define }}
the other isNoteListingComponent.razor
. This shows all the notes as well.NoteViewComponent
Razor and displays a form that allows the user to create a new note.
In this Razor component, we'll create a note list property. By replacing theOnInitializedAsync
In Blazor we go ahead and initialize our rating list property.
<!-- NoteListingComponent.razor -->@page "/"<div class="col-6"><h2>Enter your note</h2><fieldset><label for="Comment"><textarea id= "comment" cols="50" rows="6"></textarea></label></fieldset><button type="submit">Submit</button></div><div class=" col- 6"><h2>Your saved notes</h2>@if (Notes?.Any() ?? false){<ul>@foreach (var note in Notes){<NoteViewComponent Note="@note"> </ NoteViewComponent>}</ul>}else{<p>You currently have no notes saved.</p>}</div>@code {public IList<Note> Notes { get; define; }protected async replace task OnInitializedAsync(){Notes = new List<Note>();wait base.OnInitializedAsync();}}
To beBlazor code sample is available for downloadto test the things we have mentioned in this article.
Add a button event on click
We'll start by adding a button click event, and to do so, we'll use a text field to bind a value to a property.
Then we create a button. We use the button binding to a method call that adds the note to a list and removes the value from the textarea.
First we have to create onenew comment
Property. This saves the value of the textarea.
<!-- NoteListingComponent.razor -->@page "/"...@code {...public string NewComment { get; definir }...}
Next we need to tie ours.new comment
property to the value of the textarea. we will do it with her@Shortcut
Attribute. We also need to define a mandatory event. This way, we know which binding event will fire when our property is set.
<!-- NoteListingComponent.razor -->@page "/"<div class="col-6"><h2>Insira sua nota</h2><fieldset><label for="Comment"><textarea id= "Comentario" cols="50" filas="6" @bind="Nuevo comentario" @bind:event="onchange"></textarea></label></fieldset><button type="submit">Enviar< /button></div>...@código {...}
Next, we need to create a method call send. This creates a new onesupervision
instance and add it to oursWalnuts
instance list. Also, it will empty ours.new comment
Property. This ensures that when you create a note, the value in the text area is cleared.
<!-- NoteListingComponent.razor -->@using RoundTheCode.BlazorOnClick.Models@page "/"...@code {public IList<Nota> Notas { get; definieren }...protected void OnSubmitNote(MouseEventArgs mouseEventArgs){Notes.Add(new Note(NewComment));NewComment = string.Empty; }...}
Finally, we need to tie ours.OnSubmitNote
Call method for the submit button. This is done by adding a@on click
attribute and deliveryOnSubmitNote
method as value.
<!-- NoteListingComponent.razor -->@page "/"<div class="col-6">...<button type="submit" @onclick="@OnSubmitNote">Enviar</button></ div>...@código {...}
And that is. Now we can create notes in our app.
Using a button event on click as a parameter
Our next task is to take a button's onclick event as a parameter, and we'll demonstrate this to remove a note.
Let's add a delete button to oursNoteViewComponent
Component of the razor. The problem with this is that we have to delete themsupervision
our examplesupervision
list instance in ourNoteListingComponent
Razor component when the button is clicked.
So how are we going to handle a button event on click in another Razor component?
Ok, we can set up a new property in ourNoteViewComponent
Shave the component and apply the[Parameter]
attribute to him This property returns aevent callback
-Type that we can use to define the calling method in another Razor component.
<!-- NoteViewComponent.razor -->...@code {... [Parámetros] public EventCallback<MouseEventArgs> OnDeleteNote { get; definir }}
Our next task is to create the delete button. we tie oursOnDeleteNote
Evento-Callback wie das onclick-Event.
<!-- NoteViewComponent.razor -->@if (Nota != null){ <li> <span>@Note.Message</span> <span>Criado: @Note.Created.ToUniversalTime().ToString(" ddd d MMM aaaa HH:mm:ss")</span> <button type="submit" @onclick="@OnDeleteNote">Excluir</button> </li>}@code {...}
Now we must configure the call event to delete the note and we can do this by returning to oursNoteViewComponent
Razor-Components.
From there we went on and created aOnDeleteNote
invoke method. that will airsupervision
instance that we want to delete and removes it from our list of notes.
<!-- NoteListingComponent.razor -->@page "/"...@code { ... protected void OnDeleteNote(MouseEventArgs mouseEventArgs, Note note) { if (Notes?.Any(n => n == note) ??falso) { Notes.Remove(Notes.First(n => n == nota)); } }}
The last thing we have to do is link oursOnDeleteNote
event callback onNoteListingComponent
in ourNoteViewComponent
Reference. We can use the onclick step parameter because the event callback has been declared as a parameter and returns aevent callback
tip.
Also, since the calling method expects a , we can use onclick with a parametersupervision
Reference as well as the event arguments.
<!-- NoteListingComponent.razor -->...<div class="col-6"> <h2>Your saved notes</h2> @if (Notes?.Any() ?? false) { <ul> @foreach (var note in Notes) { <NoteViewComponent Note="@note" OnDeleteNote="@((e) => OnDeleteNote(e, note))"></NoteViewComponent> } </ul> } else { <p >You currently have no notes saved.</p> }</div>@code {...}

Use of other HTML events
We can't just apply a callback event on the click event. We can also do this for other events.
To demonstrate this, we'll use the onmouseover and onmouseout events to change the background color of a list of notes.
in ourNoteViewComponent
Razor, let's apply a <li> class to the existing tag. This changes when the mouse hovers over it, and changes again when the mouse hovers over it.
First we need to set up aclass name
String property.
<!-- NoteViewComponent.razor -->@if (Nota != null){ <li> <span>@Note.Message</span> <span>Criado: @Note.Created.ToUniversalTime().ToString(" ddd d MMM aaaa HH:mm:ss")</span> <button type="submit" @onclick="@OnDeleteNote">Excluir</button> </li>}@code { public string ClassName { get; definiren } ...}
Next we have to define ours.class name
property for the <li> class attribute.
<!-- NoteViewComponent.razor -->@using RoundTheCode.BlazorOnClick.Models@if (Hinweis != null){ <li class="@ClassName"> <span>@Note.Message</span> <span>Criado : @Note.Created.ToUniversalTime().ToString("ddd d MMM aaaa HH:mm:ss")</span> <button type="enviar" @onclick="@OnDeleteNote">Excluir</button> </ li>}@código {...}
The name of this class changes tomain emphasis
when the mouse is hovering and is empty once the mouse is hovering.
For this example, we'll use Blazor CSS's isolation feature. This was added in .NET 5 and allows us to add CSS to a specific Razor component.
In the CSS file is themain emphasis
The class is set to a gray background color.
/* NoteViewComponent.razor.css */.highlight {color de fondo: #ccc;}
Now we can configure our onmouseover and onmouseout call methods. This changes the value of the class name.
<!-- NoteViewComponent.razor -->...@code { ... protected void OnMouseOver(MouseEventArgs focusEventArgs) { ClassName = "highlight"; } void protegido OnMouseOut (MouseEventArgs focusEventArgs) { ClassName = string.Empty; }}
Finally, we can bind our callback events to thethe mouse above
miAlMouseFuera
Attributes in our <li> tag.
<!-- NoteViewComponent.razor -->@if (Nota != null){ <li class="@ClassName" @onmouseover="@OnMouseOver" @onmouseout="@OnMouseOut"> ... </li>} @código {...}

Asynchronous event calls
We will now see how to set up an asynchronous call method for a button onclick, which is very important when making API calls.
Using an async method call means that it is recommended to call another async method with thewait
Keyword. Also, the calling method returns aTask
tip.
To demonstrate this, we'll apply a two-second delay when creating a note. We'll do this first in our synchronous call to see how the Blazor app behaves.
Next, we'll copy the call method to create a note, but this time we'll set it up as an asynchronous callback and see how the Blazor app behaves with that two-second delay.
First we have to import themsystem diagnostics
namespace and add a new Stopwatch instance to oursOnSubmitNote
Method. When we start the timer, it goes into a while loop and repeats until two seconds have elapsed.
You will then go ahead and create the note.
<!-- NoteListingComponent.razor -->@using System.Diagnostics@page "/"...@code {... protected void OnSubmitNote(MouseEventArgs mouseEventArgs) { var stopwatch = new Stopwatch(); cronómetro.Iniciar(); while (cronómetro.Elapsed.TotalSeconds < 2) {} Notes.Add(new Note(NewComment)); NovoComentario = cadena.Vacío; } ...}
What happens is that the app slows down during this two second delay. We tried hovering over a note, which should change the background color. However, this only happens with us.OnSubmitMethod
The calling method has finished executing.
To fix this, we can go ahead and recreate our OnSubmitNote event method. But this time we create it asynchronously.
When it comes to imposing a two second delay, we can use thathomework.late
method instead of using a Stopwatch instancewait
Keyword.
<!-- NoteListingComponent.razor --><div class="col-6"> ... <button type="submit" @onclick="@(async(e) => wait OnSubmitNoteAsync(e))"> Submit</button></div>...@code { ... geschützte asynchronous Aufgabe OnSubmitNoteAsync(MouseEventArgs mouseEventArgs) { await Task.Delay(new TimeSpan(0, 0, 2)); Notes.Add(new Note(NewComment)); NewComment = string.Empty; } ...}
This now fixes the problem. Even though the two second delay is applied, we can still perform other activities in our Blazor app, such as: For example, when you hover over our note, the background color will change.
watch the video
In the video below you can see how we implemented the demos for this article.
Let's go ahead, create and delete a note, change the background color of a saved note, and test the difference between using a synchronous method and an asynchronous method.