diff --git a/src/Blazored.Modal/BlazoredModalInstance.razor.cs b/src/Blazored.Modal/BlazoredModalInstance.razor.cs index bca1b08..2fb6c93 100644 --- a/src/Blazored.Modal/BlazoredModalInstance.razor.cs +++ b/src/Blazored.Modal/BlazoredModalInstance.razor.cs @@ -94,6 +94,12 @@ public async Task CloseAsync() /// public async Task CloseAsync(ModalResult modalResult) { + //If we have a OnBeforeClose we try to invoke it here + if (Options.OnBeforeClose != null) + { + await Options.OnBeforeClose(modalResult); + } + // Fade out the modal, and after that actually remove it if (AnimationType is ModalAnimationType.FadeInOut) { diff --git a/src/Blazored.Modal/Configuration/ModalOptions.cs b/src/Blazored.Modal/Configuration/ModalOptions.cs index 702284f..6f4e50e 100644 --- a/src/Blazored.Modal/Configuration/ModalOptions.cs +++ b/src/Blazored.Modal/Configuration/ModalOptions.cs @@ -1,4 +1,6 @@ -namespace Blazored.Modal; +using Blazored.Modal.Services; + +namespace Blazored.Modal; public class ModalOptions { @@ -14,4 +16,6 @@ public class ModalOptions public ModalAnimationType? AnimationType { get; set; } public bool? UseCustomLayout { get; set; } public bool? ActivateFocusTrap { get; set; } + + public Func? OnBeforeClose { get; set; } } \ No newline at end of file diff --git a/tests/Blazored.Modal.Tests/ModalOptionsTests.cs b/tests/Blazored.Modal.Tests/ModalOptionsTests.cs index bca456f..0b2c6ca 100644 --- a/tests/Blazored.Modal.Tests/ModalOptionsTests.cs +++ b/tests/Blazored.Modal.Tests/ModalOptionsTests.cs @@ -1,4 +1,5 @@ -using Blazored.Modal.Services; +using System.Threading.Tasks; +using Blazored.Modal.Services; using Blazored.Modal.Tests.Assets; using Bunit; using Microsoft.AspNetCore.Components; @@ -266,5 +267,29 @@ public void ModalDisplaysCustomSizeClassWhenSizeIsCustom() // Assert Assert.NotNull(cut.Find(".my-custom-size")); } + + [Fact] + public void ModalTriggersOnBeforeCloseWhenModalCloses() + { + // Arrange + var onBeforeCloseTriggered = false; + var options = new ModalOptions + { + OnBeforeClose = result => + { + onBeforeCloseTriggered = result != null; + return Task.CompletedTask; + } + }; + var modalService = Services.GetService(); + var cut = RenderComponent(CascadingValue(modalService!)); + + // Act + modalService.Show("", options); + cut.Find(".bm-close").Click(); + + // Assert + Assert.True(onBeforeCloseTriggered); + } } }