How to use button's onclick event in Blazor WebAssembly (2023)

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 onesupervisionModel. HEsupervisionThe 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.razorand shows the current note. TOsupervisiontype is passed as a parameter to the Razor component to indicate which note it refers to.

(Video) Blazor WebAssembly: Button onclick event (async methods)

<!-- 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.NoteViewComponentRazor 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 theOnInitializedAsyncIn 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 commentProperty. This saves the value of the textarea.

<!-- NoteListingComponent.razor -->@page "/"...@code {...public string NewComment { get; definir }...}

Next we need to tie commentproperty to the value of the textarea. we will do it with her@ShortcutAttribute. 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 onesupervisioninstance and add it to oursWalnutsinstance list. Also, it will empty commentProperty. 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.OnSubmitNoteCall method for the submit button. This is done by adding a@on clickattribute and deliveryOnSubmitNotemethod as value.

(Video) ASP.NET CORE Blazor Tutorial for beginners 5 - Button Click Event

<!-- 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.

How to use button's onclick event in Blazor WebAssembly (1)

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 oursNoteViewComponentComponent of the razor. The problem with this is that we have to delete themsupervisionour examplesupervisionlist instance in ourNoteListingComponentRazor 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 ourNoteViewComponentShave 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 oursOnDeleteNoteEvento-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 oursNoteViewComponentRazor-Components.

From there we went on and created aOnDeleteNoteinvoke method. that will airsupervisioninstance 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 oursOnDeleteNoteevent callback onNoteListingComponentin ourNoteViewComponentReference. We can use the onclick step parameter because the event callback has been declared as a parameter and returns aevent callbacktip.

Also, since the calling method expects a , we can use onclick with a parametersupervisionReference 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 {...}
(Video) how to create button click event in blazer. how to use java script in blazor
How to use button's onclick event in Blazor WebAssembly (2)

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 ourNoteViewComponentRazor, 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 nameString 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 nameproperty 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 emphasiswhen 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 emphasisThe 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 abovemiAlMouseFueraAttributes in our <li> tag.

<!-- NoteViewComponent.razor -->@if (Nota != null){ <li class="@ClassName" @onmouseover="@OnMouseOver" @onmouseout="@OnMouseOut"> ... </li>} @código {...}
How to use button's onclick event in Blazor WebAssembly (3)

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 thewaitKeyword. Also, the calling method returns aTasktip.

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 diagnosticsnamespace and add a new Stopwatch instance to oursOnSubmitNoteMethod. 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.OnSubmitMethodThe 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.latemethod instead of using a Stopwatch instancewaitKeyword.

<!-- 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.

(Video) ASP.NET Core Blazor | DataGrid Command Buttons
(Video) Write OnClick Events in C# using Blazor and Eliminate JavaScript


1. Blazor Basics: Event Handlers
(Just Blazor Programming)
2. Getting Started with the Blazor Floating Action Button
(Syncfusion, Inc)
3. Blazor Tutorial : Event Handling - EP23
(Curious Drive)
4. MudBlazor Basics: Buttons And Alerts
(Just Blazor Programming)
5. Blazor event handling
6. Intro to C#: Extra - Blazor Web Apps 3 - Emoji Click Counter with Data Binding & Events
(Michael Hadley)


Top Articles
Latest Posts
Article information

Author: Gov. Deandrea McKenzie

Last Updated: 07/07/2023

Views: 6626

Rating: 4.6 / 5 (66 voted)

Reviews: 81% of readers found this page helpful

Author information

Name: Gov. Deandrea McKenzie

Birthday: 2001-01-17

Address: Suite 769 2454 Marsha Coves, Debbieton, MS 95002

Phone: +813077629322

Job: Real-Estate Executive

Hobby: Archery, Metal detecting, Kitesurfing, Genealogy, Kitesurfing, Calligraphy, Roller skating

Introduction: My name is Gov. Deandrea McKenzie, I am a spotless, clean, glamorous, sparkling, adventurous, nice, brainy person who loves writing and wants to share my knowledge and understanding with you.