Articles in this section
Category / Section

Show or hide toast from any page using service in Blazor

2 mins read

You can initialize single blazor toast instance and use it all over application by creating service. Refer below steps to create service to show toast from any page.

Create a toast service to inject in pages to show toast messages from anywhere. Here, title and content can be passed to show the toast message.

public class ToastOption
    public string Title { get; set; }
    public string Content { get; set; }
public class ToastService
    public event Action<ToastOption> ShowToastTrigger;
    public void ShowToast(ToastOption options)
        //Invoke ToastComponent to update and show the toast with messages  

Add the ToastService to services collection.

  • In ~/Program.cs for .NET 6 and later (Blazor Server)
  • In ~/Startup.cs for .NET 5 and .NET 3.X (Blazor Server)
  • In ~/Program.cs for .NET 6 and later (Blazor WebAssembly)
    using BlazorApp.Data;
    using Microsoft.AspNetCore.Components;
    using Microsoft.AspNetCore.Components.Web;
    using Syncfusion.Blazor;
    using BlazorApp.Components;
    // Add services to the container.

Create ToastComponent which shows SfToast based on ToastService notification.

@using Syncfusion.Blazor.Notifications;  
@inject ToastService ToastService
<SfToast @ref="Toast" Timeout=2000>  
    <ToastPosition X="Right"></ToastPosition>  
    SfToast Toast;  
    private bool IsToastVisible { get; set; } = false;  
    private ToastOption Options = new ToastOption();
    protected override void OnInitialized()
        ToastService.ShowToastTrigger += (ToastOption options) =>
            InvokeAsync(() =>
                this.Options.Title = options.Title;
                this.Options.Content = options.Content;
                this.IsToastVisible = true;

Add ToastComponent created in above step in MainLayout.razor.

@inherits LayoutComponentBase
@using BlazorApp.Components;
<div class="page">
    <div class="sidebar">
        <NavMenu />
        <div class="top-row px-4">
            <a href="" target="_blank">About</a>
        <article class="content px-4">
<ToastComponent />


Now, you can inject ToastService in any page and call ToastService.ShowToast() method to show toast notifications.

@page "/"
@using BlazorApp.Components  
@inject ToastService ToastService 
<button class="e-btn" @onclick="@ShowToast"> Show Toast</button>  
@code {  
    private void ShowToast()  
        this.ToastService.ShowToast(new ToastOption()  
            Title = "Toast Title",  
            Content = "Toast content"


View Sample in GitHub

Did you find this information helpful?
Help us improve this page
Please provide feedback or comments
Please  to leave a comment
Access denied
Access denied