Implement Toast Notifications in .Net Core

Implement Toast Notifications in .Net Core

Implementing Toast Notifications in .Net Core

Toast notifications are a great way to provide non-intrusive feedback to users in a web application. They are small pop-up messages that appear at the corner of the screen, providing information or alerts without interrupting the user’s workflow. In this blog post, we will explore how to implement toast notifications in a .NET Core application using the “NToastNotify” package.

Step-1: Adding NToastNotify Nuget Package

Go to Manage Nuget Packages and add the latest stable version of the NToastNotify package by “Nabin Karki Thapa”.

The nuget gallery link is:
https://www.nuget.org/packages/NToastNotify
and the github link is:
https://github.com/nabinked/NToastNotify

Step-2: Configure NToastNotify

Configure NToastNotify as follows:
If you are using Startup.cs: Configure it in the ConfigureServices method.
If you are using Program.cs (as in .Net Core 6.0 or later): Configure it in Program.cs as follows:

builder.Services.AddRazorPages().AddNToastNotifyToastr(new ToastrOptions()
{
ProgressBar = true,
PositionClass = ToastPositions.TopRight
});

Note: Don’t forget to add “using NToastNotify;” statement in the usings.

Use NToastNotify in the middleware pipeline just before UseRouting as:

.
.
//Use NToastNotify
app.UseNToastNotify();

app.UseRouting();
Step-3: Add NToastNotify Component to Layout

To include the necessary scripts to display toast notifications, add the following code to _Layout.cshtml file.

//Other scripts
@await Component.InvokeAsync("NToastNotify")
Step-4: Use NToastNotify

Inject the IToastNotification interface into the constructor of your page or controller (in case of MVC) as follows:

public class IndexModel : PageModel
{
private readonly IToastNotification _toastr;
public IndexModel(IToastNotification toastr)
{
_toastr = toastr;
}
.
.
}

Use the following in page or controller actions to trigger toast notification as per your need

_toastr.AddAlertToastMessage("Alert Toast Message");
_toastr.AddErrorToastMessage("Error Toast Message");
_toastr.AddInfoToastMessage("Info Toast Message");
_toastr.AddSuccessToastMessage("Success Toast Message");
_toastr.AddWarningToastMessage("Warning Toast Message");

Note: These toasts can also be triggered from javascript as follows:

toastr.alert("Alert Toast Message");
toastr.error("Error Toast Message");
toastr.info("Info Toast Message");
toastr.success("Success Toast Message");
toastr.warning("Warning Toast Message");
Conclusion

Congratulations! You have successfully implemented toast notifications in your .NET Core application using the NToastNotify library.
Feel free to explore additional features and customization options provided by NToastNotify to enhance your user experience.

Implement Toast Notifications in .Net Core
Scroll to top