Execute async method on button click in blazor

WoIIe picture WoIIe · Apr 3, 2019 · Viewed 16.6k times · Source

I created a "Razor Components" project. I am trying to execute an asynchronous method when pressing a button, but could not figure out the syntax yet.

This is my Index.razor:

@page "/"
@inject GenericRepository<Person> PersonRepository 

// ...

@foreach (var person in persons)
{
    <button onclick="@(() => Delete(person.Id))">❌</button>
}

@functions {

    // ...

    async void Delete(Guid personId)
    {
        await this.PersonRepository.Delete(personId);
    }
}

When I click the button, nothing happens. I tried various return types (e.g. Task) and stuff, but cannot figure out how to make it work. Please let me know if I need to provide more information.

Every documentation / tutorial only just works with non-async void calls on button click.

Thanks in advance.

Answer

DavidG picture DavidG · Apr 3, 2019

You need to call the Delete method properly and make it return Task instead of void:

<button onclick="@(async () => await Delete(person.Id))">❌</button>

@functions {

    // ...

    async Task Delete(Guid personId)
    {
        await this.PersonRepository.Delete(personId);
    }
}