modal-dialogblazorclientwebassemblyblazored

Refresh UI after confirmation button in a Blazored Modal popup - Blazor Client


I have a method on my page which calls a DeleteApplication.razor component and passes in the selected application:

private void deleteApplicationSubmit() 
    {
        var parameters = new ModalParameters
        {
            { nameof(DeleteApplication.applicationData), applicationData }
        };

        Modal.Show<DeleteApplication>("Are you sure you would like to delete", parameters);
    }

This opens the DeleteApplication popup. When clicking the Confirm/Delete button, the Delete method closes the popup and calls the deleteApplication method on my original screen (APIShapes):

@code {

    [CascadingParameter] BlazoredModalInstance BlazoredModal { get; set; } = default!;

    [Parameter] public ApiApplication? applicationData { get; set; }

    private APIShapes? apiShapes;

    async Task Delete()
    {
        await apiShapes.deleteApplication(applicationData);

        await BlazoredModal.CloseAsync();
    }

    async Task Cancel() => await BlazoredModal.CancelAsync();
}

The deleteApplication method then calls the api to delete the selected application.

I would expect calling the api to delete the selected item would update the UI and remove the item. Instead, the item remains until I click to load a different screen or when doing a refresh.


Solution

  • When you call deleteApplicationSubmit() in the parent component it opens the dialog and runs to completion. There's no await on the modal.Result task.

    When you click on Delete in the model - which is a sub component - it runs runs the delete against apiShapes, closes the dialog and runs to completion. It only renders the sub-component. A component render doesn't cascade a render up the render tree only down.

    You need to await the closure of the modal dialog in deleteApplicationSubmit like this:

    // Note method is now async and returns a task
    private async Task deleteApplicationSubmit() 
        {
            var parameters = new ModalParameters
            {
                { nameof(DeleteApplication.applicationData), applicationData }
            };
    
            var modal = Modal.Show<DeleteApplication>("Are you sure you would like to delete", parameters);
            
            // now await the modal closing
            var result = await modal.Result;
    
            // only runs after completion
            if (result.Cancelled)
            {
                // Do whatever
            }
            else if (result.Confirmed)
            {
                // do what you need to do to update the data that will be displayed
                // if this method is called from a UI event the component will re-render automatically
            }
        }