In this article we will learn how to create Toast Notifications in ASP.Net Core. Please read our previous article Toast Notifications in ASP.NET Core Razor Pages where we discussed how to create toast using Toast Jquery.

Here in this article we will learn how to create Toast Notifications in ASP.Net Core using toast plugin and can access the Toast notification in controller or class level in C# using below some steps.

Find Source Code

Prerequisite

We have create this application using the below configurations.

– Visual Studio 2019
– .NET Core 5.0 SDK
– ASP.Net core Toast Plugin

What is Toastr ?

Toastr is a simple JavaScript toast notification library that is small, easy to use, and extendable. It allows you to create simple toasts with HTML5 and JavaScript like this: Simply include the files in your HTML page and write a simple line of code like this: toastr.

Createing ASP.Net Core MVC application

Let’s create an ASP.Net Core MVC Application.

Install Toast notify package

The Toast Notifications is a free library for ASP.NET Core Applications. It is elegant and compatible with ASP.NET Core 3.1 and .NET 5.

You can also download it directly from https://www.nuget.org/packages/AspNetCoreHero.ToastNotification

How to use Toast package in ASP.Net Core

Let’s learn how to use Toast package in ASP.Net Core.

You need to open the _Layout file or Index.cshtml file then modify your code as shown below.

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/site.js" asp-append-version="true"></script>
@await Component.InvokeAsync("Notyf")

<form method="post" asp-controller="Home" asp-action="Index">
    <div class="text-center">
        <button class="btn btn-success" name="submit" value="Success">Toast Success</button>
        <button class="btn btn-primary" name="submit" value="Info">Toast Info</button>
        <button class="btn btn-danger" name="submit" value="Error">Toast Error</button>
        <button class="btn btn-warning" name="submit" value="Warning">Toast Warning</button>
    </div>
</form>

Code Explanation

  • Line #1-3 : We added the required jquery and css file.
  • Line #4 : @await Component.InvokeAsync(“Notyf”) is the view component that register the Toast named as “Notyf”.
  • Line #6-13 : We have create multiple buttons that can send the POST request to Home Controller.

Next, Open the Startup class, then modify your Configure method to enable toast notification while working with AJAX Requests, you will have to add the middleware into the Service Container

 public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddNotyf(config => { config.DurationInSeconds = 10; config.IsDismissable = true; config.Position = NotyfPosition.BottomRight; });
        }

Code Explanation

  • Line #4 : We have added the Toast notify services in configureservices method. Here this AddNotfy belongs several properties where you can manage the duration, position of Notification etc.
  • DurationInSeconds allows you to configure the toaster close time.
  • DurationInSeconds allows you to configure the toaster close time.
  • Position allows you to set the toast notification to appear.

In the start up class Configure method to enable toast notification while working with AJAX Requests, you will have to add the middleware into the Service Container

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //..
    app.UseNotyf();
 
    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
        endpoints.MapRazorPages();
    });
}

So you have installed ToastNotification. Next, You can open your HomeController, then modify your code as shown below.

 public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly INotyfService _notyfService;
        public HomeController(ILogger<HomeController> logger, INotyfService notyfService)
        {
            _logger = logger;
            _notyfService = notyfService;
        }

        public IActionResult Index()
        {
            _notyfService.Success("You have successfully saved the data.");
            _notyfService.Error("Exception...");
            _notyfService.Warning("Warning...");
            _notyfService.Information("Welcome to CoreSpider.", 5);
            return View();
        }

        [HttpPost]
        public IActionResult Index(string submit) 
        {
            switch (submit)
            {
                case "Success":
                    _notyfService.Success("You have successfully saved the data.");
                    break;
                case "Info":
                    _notyfService.Information("Welcome to CoreSpider.", 5);
                    break;
                case "Error":
                    _notyfService.Error("Exception...");
                    break;
                case "Warning":
                    _notyfService.Warning("Warning...");
                    break;
            }
            return View();
        }
      }

Code Explanation

  • Line #1-9 : The constructor dependency injection added to implement the notification.
  • Line #11-18: The Index action method holds the Toast notifications where we defined several types of notifications that are available in Toast notify package.
  • Line #21-38: Here we create the post method where we send the notify details of 4 buttons. According to the submit button we can segregate.

Finally, Run the application and see output like below,

Toast Notifications in ASP.NET Core

You can also customize the toast notification.

_notyfService.Custom("Custom Notification...", 10, "#B500FF", "fa fa-home");

Find Source Code

Summary

So far in this article we discussed about Toast Notifications in ASP.NET Core. If you have any suggestions then please write to us.

List Of Frequently Used Docker Commands
In this article we are going to discuss List Of Frequently Used Docker …
How to show only specific APIs on swagger in ASP.Net Core
In this article we are going to discuss how to How to Show …
List of commonly used Git commands
In this article we are going to discuss List Of Commonly Used …
Create An Amazon AWS Free Tier Account
This article explain about how to Create An Amazon AWS Free Tier …

Material Dashboard in Angular
Material dashboard in Angular

Material Dashboard is completely inspired by Google's Angular Material Design Component. Using simple command can create material dashboard.

Export data into PDF in ASP.NET MVC
Export-Data-into-PDF-SERVICE

In this example we use Dapper ORM to fetch the data from database and using the data we export into Read more

How to read external JSON file in Jquery AJAX
Javascript-Jquery-Ajax

This article explain how to read external json file. There are many ways to store JSON data in our application. Read more

ASP.NET Core Web API with MongoDB CRUD- Beginner’s Guide
ASP.NET CORE WEB API 5.0 MONGODB CRUD

This article explain CRUD operation using MongoDB in ASP.NET Core Web API. We discuss here basics of MongoDB and how Read more

  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Pin It on Pinterest

Share This