It's common to show a confirmation dialog before performing destructive actions like deleting records. Web browsers provide a built-in way to do this via confirm(message), which shows a modal dialog with a message and two buttons (OK and Cancel) and returns a boolean.
In Blazor, you can invoke JavaScript functions using IJSRuntime. To show a confirm dialog, call JSRuntime.InvokeAsync<bool>("confirm", "message").
Here's a full example:
Razor
@page "/"
@inject IJSRuntime JSRuntime
<h1>Customers</h1>
@* Grid component from the previous post: https://www.meziantou.net/creating-a-datagrid-component-in-blazor.htm *@
<Grid Items="customers" class="table">
<GridColumn TRowData="Customer" Expression="c => c.Id" />
<GridColumn TRowData="Customer" Expression="c => c.Name" />
<GridColumn TRowData="Customer" Expression="c => c.Email" />
<GridColumn TRowData="Customer" Context="customer">
<button class="btn btn-danger" @onclick="() => Delete(customer)">Delete</button>
</GridColumn>
</Grid>
@code{
List<Customer> customers = GetCustomers();
async Task Delete(Customer customer)
{
if (!await JSRuntime.InvokeAsync<bool>("confirm", $"Are you sure you want to delete the customer '{customer.Name}'?"))
return;
customers.Remove(customer);
}
}
To reuse this across multiple components, extract it into an extension method:
C#
public static class ConfirmExtensions
{
public static ValueTask<bool> Confirm(this IJSRuntime jsRuntime, string message)
{
return jsRuntime.InvokeAsync<bool>("confirm", message);
}
}
#Addition resources
Do you have a question or a suggestion about this post? Contact me!