Toast Notifications in ASP.NET Core

Toast Notifications in ASP.NET Core

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

Material Dashboard in Angular

Material Dashboard in Angular

In this article we will learn how to create & use material dashboard in angular. Please follow our previous article How to use angular material in angular. If you are new to angular then please explore our Angular Series where we discussed step by step process of angular from beginner to advance level.

  • We create a sample angular 9 application and there use in-built angular dashboard functionality.
  • Here we can see how to add angular material dashboard dynamically with card. We can do change the dashboard card columns and rows dynamically.

Add Material Design in Angular

To create the angular application use the below command. ng-material-dashboard is the project name.

ng new ng-material-dashboard

To add the material design in angular just follow the below command. Also you can find the details about our previous article How to use angular material in angular.

ng add @angular/material

After type the command in terminal window and hit enter then a prompt will ask to choose which material template want to install into the application like this. Let’s install first one “Indigo/Pink” you can chhose any other theme just navigate to the link.

material theme

Generating a Material Dashboard

To generate a material dashboard use the below command. This command should create a starter dashboard component.

Synatax

ng generate @angular/material:material-dashboard --name = <Name of Dashboard>

material-dashboard is a starter component, which generates a group of the materialized components in the form of the dashboard by just providing a name. To create the dashboard run the below command

ng generate @angular/material:material-dashboard --name material-dashboard

And as you can see in the console, there are a few files created inside the app directory with a component name provided. The file structure looks like the below screen.

material-dashboard

After installing this you can see the material-dashboard ts, html and css file automatically created.

Materiel Dashboard component

app.module.ts

You can see here when the material-dashboard component is created it automatically add the required module inside app.module.ts

materiel-app-module

material-dashboard.component.ts

In the below typescript we create a Cards list that return how many columns and rows. You can change the column and row to set dynamically.

import { Component } from '@angular/core';
import { map } from 'rxjs/operators';
import { Breakpoints, BreakpointObserver } from '@angular/cdk/layout';
@Component({
  selector: 'app-material-dashboard',
  templateUrl: './material-dashboard.component.html',
  styleUrls: ['./material-dashboard.component.css']
})
export class MaterialDashboardComponent {
  /** Based on the screen size, switch from standard to one column per row */
  cards = this.breakpointObserver.observe(Breakpoints.Handset).pipe(
    map(({ matches }) => {
      if (matches) {
        return [
          { title: 'Card 1', cols: 1, rows: 1 },
          { title: 'Card 2', cols: 1, rows: 1 },
          { title: 'Card 3', cols: 1, rows: 1 },
          { title: 'Card 4', cols: 1, rows: 1 }
        ];
      }
      return [
        { title: 'Card 1', cols: 2, rows: 1 },
        { title: 'Card 2', cols: 1, rows: 1 },
        { title: 'Card 3', cols: 1, rows: 2 },
        { title: 'Card 4', cols: 1, rows: 1 }
      ];
    })
  );
  constructor(private breakpointObserver: BreakpointObserver) {}
}

material-dashboard.component.html

The below snippet is a basic building block which was generated by the component generator. Dynamically bind the cards from material-dashboard.component.ts and using *ngFor iterate the result through material components.

<div class="grid-container">
  <h1 class="mat-h1">Dashboard</h1>
  <mat-grid-list cols="2" rowHeight="350px">
    <mat-grid-tile *ngFor="let card of cards | async" [colspan]="card.cols" [rowspan]="card.rows">
      <mat-card class="dashboard-card">
        <mat-card-header>
          <mat-card-title>
            {{card.title}}
            <button mat-icon-button class="more-button" [matMenuTriggerFor]="menu" aria-label="Toggle menu">
              <mat-icon>more_vert</mat-icon>
            </button>
            <mat-menu #menu="matMenu" xPosition="before">
              <button mat-menu-item>Expand</button>
              <button mat-menu-item>Remove</button>
            </mat-menu>
          </mat-card-title>
        </mat-card-header>
        <mat-card-content class="dashboard-card-content">
          <div>Card Content Here</div>
        </mat-card-content>
      </mat-card>
    </mat-grid-tile>
  </mat-grid-list>
</div>

material-dashboard.component.css

This style sheet file contains different classes to provide different positioning and directions throughout the page.

.grid-container {
  margin: 20px;
}
.dashboard-card {
  position: absolute;
  top: 15px;
  left: 15px;
  right: 15px;
  bottom: 15px;
}
.more-button {
  position: absolute;
  top: 5px;
  right: 10px;
}
.dashboard-card-content {
  text-align: center;
}

These files are automatically generated for creating a Material Dashboard.

Now, the last step is to execute our dashboard app. For that, just go to the app.component.html file and remove all of the content and just add the material-dashboard tag like below;

<app-material-dashboard> </app-material-dashboard>

All the changes has been made, let’s run the application and see the output like below;

Material starter Dashboard template

You can do place the dynamic content/image into the card accordingly in material-dashboard.component.ts. Let’s say we add a image field in card like below;

return [
        { title: 'Card 1', cols: 2, rows: 1, imagepath: '/assets/img1.png' },
        { title: 'Card 2', cols: 1, rows: 1, imagepath: '/assets/img2.png' },
        { title: 'Card 3', cols: 1, rows: 2, imagepath: '/assets/img3.png' },
        { title: 'Card 4', cols: 1, rows: 1 , imagepath: '/assets/img4.png' }
      ];

And in the material-dashboard.component.html add like this.

Image add
Image add

After run the application you can see the image are displayed on the card. According to your dashboard design you can do the stuff.

Image bind on Card

Summary

So far this article we discuss how to use material dashboard in angular. If have any suggestion about this article please give your feedback.

That’s a wrap for this article. I hope that it cleared about Material Dashboard in Angular. Please write to us if have any.

Have you enjoyed this post and found it useful? If so, please consider supporting me:

Buy me a coffeeBuy me a coffee

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

How to use angular material in angular
How to use angular material in angular

UI component infrastructure and Material Design components for mobile and desktop Angular web applications.

Export data into PDF in ASP.NET MVC

Export data into PDF in ASP.NET MVC

In this article we will discuss how to export PDF in ASP .NET MVC. Here we discuss export into PDF without using any 3rd party libraries. Please go through our previous article Export data into Excel in ASP.NET MVC. If are new to in ASP .NET MVC for step by step access please explore ASP .NET MVC Series.

How to export PDF in ASP.NET MVC

Create the Project in ASP .NET MVC and connect database and fetch the record using Dapper ORM and export the data into PDF.

  • Create a ASP.NET MVC application using Visual Studio.
  • We select as Empty project with targeting to ASP.NET MVC.
  • Create a Controller inside the controllers folder, let’s name as “EmployeeController.cs”
  • The Employee Db contains a employee table that holds the employee information. The script are find below;
Database Script
Employee table script
Employee.cs

Add a employee property class in Models folder.

Employee Property Class
Connection string

Declare the connection string in Web.config like below;

 <connectionStrings>
    <add name="ConnectionString" connectionString="Data Source=corespider;Initial Catalog=EmployeeDb;Persist Security Info=True;User ID=sa;password=**********;Pooling=false;Connect Timeout=300000" providerName="System.Data.SqlClient" />
  </connectionStrings>

To connect with database and fetch the record, her ewe use Dapper ORM.

What is Dapper ?

Dapper is an object-relational mapping product for the Microsoft .NET platform: it provides a framework for mapping an object-oriented domain model to a traditional relational database. Its purpose is to relieve the developer from a significant portion of relational data persistence-related programming tasks.

Add Dapper package in Nuget
export data into PDF in ASP.NET MVC-Dapper
Dapper Package
EmployeeRepository.cs

Add another class in Models folder to retrieve the employee information from database.

EmployeeRepository.cs
Code Explanation
  • Here We create the IDbConnection that hold the connection string information.
  • Using Dapper ORM fetch the employee tables.
  • In real-time application you may use Stored procedure instead of text.
  • Dapper ORM directly return the list of employee.
EmployeeController.cs
Employee information
Code Explanation
  • Here we create object of the employee repository class.
  • In the Index() we fetch the employee list and return to the view.
Index.cshtml
Code Explanation
  • Here we use scaffold technique to create list of employees.
  • Added a button to Export the data into PDF.
  • Export is the action method and Employee is the Controller.

Export Action method to convert PDF

Code Explanation
  • In the export Post method we fetch the employee information.
  • To export data into PDF we use Gridview controls that are in System.Web.UI.WebControls namespace.
  • In Gridview controls hold the employee list.
  • In the string writer and string Reader st the PDF using HTMLWorker.
  • Response content type as PDF and finally append the PDFdoc that export into PDF.

Run the application and see the output

export data into PDF in ASP.NET MVC-export pdf
Export Data

After click the export button it convert the above data into PDF like below;

export data into PDF in ASP.NET MVC-PDF
Export PDF
Export PDF
Export to PDF in ASP NET MVC

Conclusion

This article explained how to export PDF in ASP.NET MVC . In this example we use Dapper ORM to fetch the data from database and using the data we export into PDF using Gridview controls that are available in System.Web.UI.WebControl namespace. Please free to feel if have any suggestion or feedback about this article.

Export data into Excel in ASP.NET MVC
Export-data-into-Excel

In this example we learn how to export the data into MS Excel in ASP.NET MVC without using any 3rd 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

How to read external JSON file in Jquery AJAX

How to read external JSON file in Jquery AJAX

In this article we discuss read external JSON file in Jquery Ajax. If you are new to Jquery then please explore our Jquery Series. There are many ways to store JSON data in our application. We can store JSON in an array or in an external file. There are many ways to read JSON data from external files, here we see how it be done using Jquery Ajax.

What is Ajax ?

Ajax is a set of web development techniques using many web technologies on the client side to create asynchronous web applications. With Ajax, web applications can send and retrieve data from a server asynchronously without interfering with the display and behavior of the existing page.

Let’s you have a external JSON file named as sample.json and it holds the JSON value like below;

{"first_name" : "John", "last_name" : "Smith", "location" : "USA"}

How to read JSON file in Jquery AJAX

Here let’s create a HTML and use Jquery Ajax to read the json.

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $.ajax({
            type: "GET",
            url: "./json/sample.json",
            success: function (response) {
                console.log(response)
                $("div").append("First Name : " + response.first_name+ "<br/>Last Name : " +response.last_name+ 
                                   "<br/> Address : "   + response.location);
            }
        });
    </script>
<body>
    <div></div>
</body>
</head>
</html>

Code Explanation

On the above we create a AJAX method to read the external JSON fileby passing in the ajax URL. After getting response print the result in the DIV tag. Also if we open the browser console window you can see the output like below;

After run the application you can see the output like below;

Read external JSON file using Jquery AJAX

Conclusion

This article explained how to use external Json file in Jquery Ajax. If have any suggestion about this article please give your feedback.

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

Pin It on Pinterest