13th Sep 2021

How to implement Toast alert in Blazor

.NET

Written By, Jalpesh Nakum

Overview

Hello Devs,
Hope you are excited to go further into your journey of learning Blazor. Lets build interactive web UIs using C# instead of JavaScript. In this blog, we will take a look at how to apply a toaster in Blazor.

To apply Toaster in Blazor we need to follow some step is as below:

Install Package

  • Install-Package Blazored.Toast

install-package

  • We also Install by using CLI run below line
    dotnet add package Blazored.Toast

Register Service

For Blazor Server Add Service in

Add Imports

Add 2 imports file in our _import.razor file

Add Blazor Toaster in  Component

  • Add <BlazoredToasts /> tag in our mainLayout.razor
  • When we add <BlazoredToasts /> in our application then below options are available.
    • InfoClass
    • SuccessClass
    • WarningClass
    • ErrorClass
    • InfoIcon
    • SuccessIcon
    • WarningIcon
    • ErrorIcon
    • IconType(Default : IconType.FontAwesome)
    • Position(Default : ToastPosition.TopRight)
    • Timeout(Default : 5sec)

By, default we don’t need to add any type of style in our application but when we add style or modify any default style, then we can use above style as per our requirement

Example:

Add below reference in our mainLayout.razor component

Add references

  • Add the following line inside our <head> tag of your _Host.cshtml for Blazor Server or Index.html for Blazor WebAssembly
  • For Minified use :
    <link href=”_content/Blazored.Toast/blazored-toast.min.css” rel=”stylesheet” />
  • For Unminified use :
    <link href=”_content/Blazored.Toast/blazored-toast.css” rel=”stylesheet” />

 Inject ToastService

  • Now, we need to Inject IToastService in our required component, in those we need to use Toaster
  • You can use the following methods depending on which type of toast you want to display. Here we need to pass the message but heading is optional

  1. ShowInfo:
    toastService.ShowInfo(“This is Info message”);
  2. ShowSuccess:
    toastService.ShowSuccess(“This is Success message with title”,”SUCCESS”);
  3. ShowWarning:
    toastService.ShowWarning(“This is Warning message”);
  4. ShowError:
    toastService.ShowError(“This is Error message with title”,”Error”);

If you want to Show Progress bar of our Toaster then in Blazor Toaster we have inbuilt this functionality we need to add below line of code.

If you want to Remove Toster when Page is Navigating one page to new one that time you need to set RemoveToastOnNavigation set true.

Here is the code of my toaster.razor Component

Code :

Output : 

output

Conclusion

The main motive of this blog is to provide a fundamental understanding of toaster usage in Blazor. Thank you for reading, hope you are clear about How to apply Toaster in Blazor.

Written By,

.NET Developer at Yudiz Solutions Pvt. Ltd