Search code examples
blazor-server-sidetoastblazor-bootstrap

Global toasts service Bootstrap for Blazor server application


I am working on a project with Blazor Server (.NET 8) & Bootstrap (2.0.0) and I would like to use the toast component of Bootstrap. I wanted to use The Global toast service to display my toasts when I for example log in.

I followed the Blazor Bootstrap docs and demo's but this does not work.

MainLayout.razor:

@inherits LayoutComponentBase

<div class="page">
    <div class="sidebar">
        <NavMenu />
    </div>

    <main>
        @* <div class="top-row px-4">
            <a href="https://learn.microsoft.com/aspnet/core/" target="_blank">About</a>
        </div> *@
        <article class="content px-4">
            @Body
        </article>
    </main>
    <Toasts class="p-3" Placement="ToastsPlacement.TopRight" />
</div>

<div id="blazor-error-ui">
    An unhandled error has occurred.
    <a href="" class="reload">Reload</a>
    <a class="dismiss">🗙</a>
</div>

Login.razor:

(...)
@code {
    [Inject] protected ToastService ToastService { get; set; }

    private async Task LogIn()
    {
        (Code to login in database)
        if (getAuthenticationFromDatabase != null && getAuthenticationFromDatabase.Succeeded)
        {
            ToastService.Notify(new(ToastType.Success, "Welcome"));
            ...
            Navigation.NavigateTo("/"); //redirect to go back to homepage
        }
    }
}

Note: When I move the Toasts tag of Bootstrap to the login.razor, then the toast will show up.

Can anybody help and explain why it does not show up when the toast tag is in MainLayout.razor?

Thanks!


Solution

  • I ran into this same issue as well. I was able to resolve it by setting the @renderMode="@InteractiveServer" on the HeadOutlet and Routes components in the App.razor file

    ...
        <HeadOutlet @rendermode="@InteractiveServer" />
    </head>
    
    <body>
        <Routes @rendermode="@InteractiveServer" />
    ...
    

    This was shown under the Sample Code => App.razor section in the Getting started - Blazor WebApp (.NET 8) - Interactive render mode Server page

    Setting that allows the entire app to render in InteractiveServer mode. Check out the Apply a render mode to the entire app section in the ASP.NET Core docs on ASP.NET Core Blazor ender modes to get better understanding of that.

    As to why that's required. I'm guessing that the Toast component when used globally requires InteractiveServer for it to render properly.