Toasts pop-up and automatic closure issues

929Free 601 Reputation points
2025-04-25T06:55:54.0766667+00:00

hello, I implemented a pop-up box using JavaScript, Here is the JavaScript calling scheme.

Toasts:

                <div class="toast-container bottom-0 end-0 p-3">
                    <div id="deptStatusChangeTip" class="toast align-items-center text-bg-primary " role="alert" aria-live="assertive" aria-atomic="true">
                        <div class="d-flex">
                            <div class="toast-body">
                                @showTipMessage.
                            </div>
                            <button type="button" class="btn-close me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
                        </div>
                    </div>
                </div>

Javascript function :

    function ShowChangeDeptStatusTipToasts()
    {
        const deptStatusChangeToast = document.getElementById('deptStatusChangeTip')

        const deptStatusChangeToastWindow = bootstrap.Toast.getOrCreateInstance(deptStatusChangeToast)

        deptStatusChangeToastWindow.show();
    }

c# code :

        
showTipMessage = "TestMessage";  
               
StateHasChanged();          

await JSRuntime.InvokeVoidAsync("ShowChangeDeptStatusTipToasts");

but, I want to implement pop-up and automatic window closure through C # callin, Can you teach me? Thank you

Blazor Training
Blazor Training
Blazor: A free and open-source web framework that enables developers to create web apps using C# and HTML being developed by Microsoft.Training: Instruction to develop new skills.
32 questions
{count} votes

Accepted answer
  1. Pradeep M 8,660 Reputation points Microsoft External Staff Moderator
    2025-04-25T07:29:47.2566667+00:00

    Hi 929Free  

    Thank you for reaching out to Microsoft Q & A forum. 

    To enable automatic closure of the toast via C#, you can update your JavaScript function to accept a timeout value: 

    function ShowChangeDeptStatusTipToastsWithTimeout(durationInMs) {
        const toastEl = document.getElementById('deptStatusChangeTip');
        if (!toastEl) return;
        const toast = new bootstrap.Toast(toastEl, { autohide: true, delay: durationInMs });
        toast.show();
    }
    
    

    Then, from your Blazor C# code, you can invoke it like this: 

    showTipMessage = "TestMessage";
    StateHasChanged();
    await JSRuntime.InvokeVoidAsync("ShowChangeDeptStatusTipToastsWithTimeout", 3000); // 3 seconds
    
    

     This will display the toast message and automatically dismiss it after the specified duration.

    If you have found the answer provided to be helpful, please click on the "Accept answer/Upvote" button so that it is useful for other members in the Microsoft Q&A community.


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.