I was trying to find a way to close a bootstrap modal from a C# method inside a blazor webassembly component.
Bellow is a solution I came up with. It involves the use of IJSRuntime to call a javascript method to manipulate the bootstrap modal. I'm sure there are other ways to solve this.
CodePudding user response:
The bootstrap modal can be closed via javascript:
Create a javascript wwwroot/js/site.js file with the code:
export function CloseModal(modalId) {
$(modalId).modal('hide');
}
Include the script in index.html at the end of the body:
...
<script src="js/site.js"></script>
</body>
There exists a parent component calling the modal:
ParentComponent.razor
<!-- Button trigger modal -->
<button type="button" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<ModalComponent />
@code {
}
Then there is a modal component containing the modal: (We are making use of IJSRuntime to call js from C# code)
ModalComponent.razor
@inject IJSRuntime js
<!-- Modal -->
<div id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div role="document">
<div >
<div >
<h5 id="exampleModalLabel">Modal title</h5>
<button type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div >
...
</div>
<div >
<button type="button" data-dismiss="modal">Close</button>
<button type="button" >Save changes</button>
</div>
</div>
</div>
</div>
@code {
IJSObjectReference JsObjectRef { get; set; }
protected override async Task OnAfterRenderAsync(bool first)
{
JsObjectRef = await js.InvokeAsync<IJSObjectReference>("import", "/js/site.js");
}
async Task SomeMethod(){
//some logic
//call the js function to close the modal
await JsObjectRef.InvokeVoidAsync("CloseModal", "#exampleModal");
}
}
Now the modal can be closed from the c# code, say for example when a submit method is called.
This logic has worked for me. I'm sure there are other better solutions for this out there, nevertheless I really hope it helps anyone in need.
Peace