Table of Contents
Introduction
A Blazor toast component is a user interface used for displaying messages or alerts to end users. Messages that appear briefly and then fade away usually provide information without disrupting the user’s workflow. In this post, we will see how to create a Blazor toast component using only C#, Html and CSS.
Creating a Toast Solution and adding a Razor class library project
Open Visual Studio and create a blank solution named Toast
and add a new Razor Class library named Dnc.Common.Razor
to the solution. I selected .NET 8 (Long Term Support) as the target Framework.
Creating the DncWrapper component – Unfinished
A wrapper component is a component that encapsulates other components or elements within itself, There are many uses for this encapsulation, Including adding functionality, changing behavior, or simply changing the appearance of the encapsulated content.
In the previous post Creating a blazor loading spinner component, we created a wrapper component that provides the blazor loading spinner functionality for the wrapped content.
The wrapper component encapsulates the Body
property in the MainLayout
component, and makes the blazor toast component available to all child components.
We start by creating a new folder called Wrapper in the Dnc.Common.Razor
project and add a new class file called DncWrapperComponent.cs
, which is derived from the ComponentBase
class.
namespace Dnc.Common.Razor.Wrapper
{
public class DncWrapperComponent:ComponentBase
{
[Parameter]
public RenderFragment ChildContent { get; set; }
}
}
In the Wrapper folder create a new file called DncWrapper.razor
, which inherits from the DncWrapperComponent
class, and enter the following mark-up.
@inherits DncWrapperComponent
<div class="dnc-wrapper">
<CascadingValue Value="this">
@ChildContent
</CascadingValue>
</div>
The DncWrapperComponent
component instance is passed on as a complex type to all descendent components. The Descendant components can then perform actions with the instance by using its methods and binding to its properties.
We will add the methods of the Blazor Toast component to the wrapper component later.
Creating the Blazor Toast service
First we need to create a new folder called Enums and add an enum called MessageType
. Here we need to add the 4 different message types as follows.
namespace Dnc.Common.Razor.Enums
{
public enum MessageType
{
Success = 0,
Error = 1,
Warning = 2,
Info = 3
}
}
Second create a new folder called Interfaces in the Dnc.Common.Razor
project and add a new interface file called IToastService
.
namespace Dnc.Common.Razor.Interfaces
{
public interface IToastService
{
Task ShowMessage(string message, MessageType messageType, TimeSpan? duration = null);
Task ShowSuccessMessage(string message, TimeSpan? duration = null);
Task ShowErrorMessage(string message, TimeSpan? duration = null);
Task ShowWarningMessage(string message, TimeSpan? duration = null);
Task ShowInfoMessage(string message, TimeSpan? duration = null);
}
}
The IToastService
interface contains methods that are responsible for displaying the messages for a specific time or permanently.
Creating the Blazor Toast Component
A Blazor Toast component is responsible for displaying messages to end users.
The message appears for a short time when you set the time span value and then disappears, or can be displayed until the end user closes it by clicking the close button.
The Blazor Toast component is created using C#, Html and CSS only.
Create a new folder called Toast and add a class file called DncToastComponent
, which is derived from the ComponentBase
class and implements the IToastService
and IDisposable
interfaces as follows.
namespace Dnc.Common.Razor.Toast
{
public class DncToastComponent : ComponentBase, IToastService, IDisposable
{
[CascadingParameter]
protected DncWrapperComponent DncWrapper { get; set; }
[Inject]
protected NavigationManager NavigationManager { get; set; }
protected MarkupString Message { get; set; }
protected bool Show { get; set; }
protected string ToastBackgroundColor { get; set; }
private string currentLocation = string.Empty;
protected override void OnInitialized()
{
DncWrapper.SetToastService(this);
}
public async Task ShowSuccessMessage(string message, TimeSpan? duration = null)
{
await ShowMessage(message, MessageType.Success,duration);
}
public async Task ShowErrorMessage(string message, TimeSpan? duration = null)
{
await ShowMessage(message, MessageType.Error, duration);
}
public async Task ShowWarningMessage(string message, TimeSpan? duration = null)
{
await ShowMessage(message, MessageType.Warning, duration);
}
public async Task ShowInfoMessage(string message, TimeSpan? duration = null)
{
await ShowMessage(message, MessageType.Info, duration);
}
public async Task ShowMessage(string message, MessageType messageType, TimeSpan? duration = null)
{
Show = true;
Message = (MarkupString)message;
switch (messageType)
{
case MessageType.Success:
ToastBackgroundColor = "dnc-toast-success";
break;
case MessageType.Error:
ToastBackgroundColor = "dnc-toast-error";
break;
case MessageType.Warning:
ToastBackgroundColor = "dnc-toast-warning";
break;
case MessageType.Info:
ToastBackgroundColor = "dnc-toast-info";
break;
}
currentLocation = NavigationManager.Uri;
NavigationManager.LocationChanged -= NavigationHandler;
NavigationManager.LocationChanged += NavigationHandler;
StateHasChanged();
if (duration != null)
{
await Task.Delay((TimeSpan)duration);
Clear();
}
}
protected void Close()
{
Show = false;
}
public void Clear()
{
Show = false;
StateHasChanged();
}
public void Dispose()
{
NavigationManager.LocationChanged -= NavigationHandler;
}
private void NavigationHandler(object sender, LocationChangedEventArgs args)
{
if(!string.Equals(args.Location, currentLocation, StringComparison.OrdinalIgnoreCase)){
Clear();
NavigationManager.LocationChanged -= NavigationHandler;
StateHasChanged();
}
}
}
}
We define a few properties and fields that will be used in the mark up, and the DncWrapper
component is injected into the DncToast
component as a cascading parameter.
Next we override the OnInitialized
of Blazors component lifecycle events to make the methods of the DncToast
component available in the DncWarpper
component by using the SetToastService
method that is added to the DncWrapper
component in the next section.
Then we created an event handler NavigationHandler
, which is responsible for closing the message when the location changes.
Finally, ShowMessage
, which is used by the other methods to display the different type of messages, sets the style of the toast message and sets the Show
property to true
, so that the blazor toast component is visible for a certain time if the duration
is not null
.
The mark up of the Toast component is simple and self-explanatory. In the Toast folder, create a new file called DncToast.razor
, which inherits from the DncToastComponent
class, and enter the following mark-up.
@inherits DncToastComponent
<div id="dnc-toast" class="container">
@if(Show)
{
<div class="d-flex justify-content-between dnc-toast @ToastBackgroundColor">
<div class="toaster-content d-flex justify-content-center flex-column">
@Message
</div>
<div class="dnc-toast-close">
<a href="javascript:void(0)" @onclick="Close">
<i class="fa fa-times dnc-toast-close"></i>
</a>
</div>
</div>
}
</div>
Completing the DncWrapper component
The DncWrapper
component wraps the entire application and provides the functionality of the Toast Component for all its children.
First, edit the DncWrapperComponent
by adding the following methods.
namespace Dnc.Common.Razor.Wrapper
{
public class DncWrapperComponent:ComponentBase
{
[Parameter]
public RenderFragment ChildContent { get; set; }
protected IToastService ToastService { get; set; }
public void SetToastService(IToastService toastService)
{
ToastService = toastService;
}
public void ShowSuccessMessage(string message, TimeSpan? duration = null)
{
ToastService?.ShowSuccessMessage(message, duration);
}
public void ShowErrorMessage(string message, TimeSpan? duration = null)
{
ToastService?.ShowErrorMessage(message, duration);
}
public void ShowWarningMessage(string message, TimeSpan? duration = null)
{
ToastService?.ShowWarningMessage(message, duration);
}
public void ShowInfoMessage(string message, TimeSpan? duration = null)
{
ToastService?.ShowInfoMessage(message, duration);
}
}
}
The solution should look like this.

Also read https://dotnetcoder.com/creating-a-reusable-blazor-modal-component/
Use of the Blazor Toast in the Blazor Web App
In this section we will learn how to use our custom Blazor Toast in the Blazor application.
First, add a new Blazor Web App project template named Dnc.Toast.WebApp
to the solution. I selected .NET 8 (Long Term Support) as the target Framework.

Second reference the Dnc.Common.Razor
project to the Dnc.Toast.WebApp
project, and edit the _Imports.razor
as follows.
@using Dnc.Common.Razor.Wrapper
@using Dnc.Common.Razor.Toast
Then encapsulate the MainLayout.razor
component with the DncWrapper
component as follows.
@inherits LayoutComponentBase
<DncWrapper>
<DncToast/>
<div class="container">
@Body
</div>
</DncWrapper>
Finally, insert the following code into the Home.razor
and start the application.
<div class="container">
<div class="row">
<div class="col">
<div class="center-block">
<div class="btn-group-vertical" role="group" aria-label="Vertical button group">
<button class="btn dnc-btn-success" @onclick="ShowSuccess">Show success message</button>
<button class="btn dnc-btn-error" @onclick="ShowError">Show error message</button>
<button class="btn dnc-btn-warning" @onclick="ShowWarning">Show warning message</button>
<button class="btn dnc-btn-info" @onclick="ShowInfo">Show info message</button>
</div>
</div>
</div>
</div>
</div>
@code {
[CascadingParameter]
public DncWrapper DncWrapper { get; set; }
public void ShowSuccess()
{
// DncWrapper.ShowSuccessMessage("This is Success Message", TimeSpan.FromSeconds(5));
DncWrapper.ShowSuccessMessage("This is Success Message");
}
public void ShowError()
{
// DncWrapper.ShowErrorMessage("This is Error Message", TimeSpan.FromSeconds(5));
DncWrapper.ShowErrorMessage("This is Error Message");
}
public void ShowWarning()
{
// DncWrapper.ShowWarningMessage("This is Warning Message", TimeSpan.FromSeconds(5));
DncWrapper.ShowWarningMessage("This is Warning Message");
}
public void ShowInfo()
{
// DncWrapper.ShowInfoMessage("This is Info Message", TimeSpan.FromSeconds(5));
DncWrapper.ShowInfoMessage("This is Info Message");
}
}


Conclusion
In this post we created a Blazor Toast component that can be used in your different projects. We started by creating a wrapper component that encapsulates the Body
property in the MainLayout
component, which provides the Blazor Toast functionality for the encapsulated content. I did not go through the CSS code because it’s off topic for this post.
The code for the Blazor Toast component can be found Here.
Also read https://dotnetcoder.com/creating-a-blazor-confirm-dialog-component/
Enjoy This Blog?
Discover more from Dot Net Coder
Subscribe to get the latest posts sent to your email.