'bootstrap 5 modal returns to calling method before the modal-popup buttons are clicked
My project is Blazor WASM-hosted, .Net 6, C#, VS-2022, Bootstrap v5. I have coded up a blazor component <MessageBoxComponent ... > to handle the modal-html and button-click-code to hide/terminate the popup. I have got so far that it works like a js-"alert()"-function in that the text and buttons are displayed and clicking a button returns the "button-number" of the clicked button which is also correct. The launching of this modal-popup occurs in the "handle-submit" click of my Blazor CRUD component (not a page) -- code follows:
public async Task HandleSubmit() {
// --- other code --- //
refMessageBox.DoShow(); <- NOTE: I expect this to be MODAL, but it is NOT modal, it returns immediately.
switch (MsgBoxReturnedValue) {
case 1:
// --- continue with SAVE code --- //
await OnSavedCRUD.InvokeAsync(kvPairAction);
break;
default:
break;
}
// --- other code --- //
}
The "DoShow()" code within the modal-component follows:
public void DoShow() {
_IsShow = true;
StateHasChanged();
}
The event returned back after user selects a button in the modal-popup code follows:
void MessageBoxReturnChanged(int pButtonPressed) {
// Event coming from MessageBoxComponent.
MsgBoxReturnedValue = pButtonPressed;
switch (pButtonPressed) {
case 1:
// --- continue with SAVE code --- //
await OnSavedCRUD.InvokeAsync(kvPairAction);
break;
default:
break;
}
}
What happens in the HandleSubmit-function is the call to refMessageBox.DoShow(); returns immediately and therefore there is no way to act upon the user's button-click from the modal-component, since the click-event occurs after the calling function is finished.
I am missing some technique? -- do I need javascript functions to control the events of the modal-popup? Your questions, comments and answers are welcome...thanks...John
Solution 1:[1]
You can do what you want by making the modal show as async function which return a task and use it by await. As you may know Blazor WAsm is a single thread process and it waits for your answer to be returned. for example use this simple Prompt version of your modal (where message is get from user):
private async Task showPrompt()
{
message = await _js.Prompt(message);
}
where:
function showPrompt(message) {
return prompt(message, 'Type anything here');
}
Also be sure to hide your modal at the end of your form submission.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mehdi Mowlavi |
