Display Bootstrap Alerts Dynamically From ASP.NET Core 3.1 MVC

Introduction

 
This article introduces how to display bootstrap alerts dynamically from an ASP.NET Core 3.1 MVC Application.
 
Bootstrap provides us with an easy way to create predefined alerts. Bootstrap alerts are available for any length of text, as well as an optional close button. An example of a bootstrap alert is given below.
  1. <div class="alert alert-success alert-dismissible">    
  2.    <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>    
  3.    <strong>Success!</strong> This alert box could indicate a successful or positive action.    
  4.  </div>     
Let's follow the below steps to show the alerts dynamically from a simple ASP.NET Core 3.1 MVC Application.
 
Step 1
 
Create an ASP.NET Core 3.1 MVC Web App.
 
 
Step 2
 
Add a new folder and add an Enum into that folder and give a suitable name like this.
 
   
 
Step 3
 
Now create a common service like this.
 
 
The code snippet for the CommonServices.cs class is given below. A new static method ‘ShowAlert’ is added here which takes two parameters and returns html as string.
  1. public class CommonServices {  
  2.     public static string ShowAlert(Alerts obj, string message) {  
  3.         string alertDiv = null;  
  4.         switch (obj) {  
  5.             case Alerts.Success:  
  6.                 alertDiv = "<div class='alert alert-success alert-dismissable' id='alert'><button type='button' class='close' data-dismiss='alert'>×</button><strong> Success!</ strong > " + message + "</a>.</div>";  
  7.                 break;  
  8.             case Alerts.Danger:  
  9.                 alertDiv = "<div class='alert alert-danger alert-dismissible' id='alert'><button type='button' class='close' data-dismiss='alert'>×</button><strong> Error!</ strong > " + message + "</a>.</div>";  
  10.                 break;  
  11.             case Alerts.Info:  
  12.                 alertDiv = "<div class='alert alert-info alert-dismissable' id='alert'><button type='button' class='close' data-dismiss='alert'>×</button><strong> Info!</ strong > " + message + "</a>.</div>";  
  13.                 break;  
  14.             case Alerts.Warning:  
  15.                 alertDiv = "<div class='alert alert-warning alert-dismissable' id='alert'><button type='button' class='close' data-dismiss='alert'>×</button><strong> Warning!</strong> " + message + "</a>.</div>";  
  16.                 break;  
  17.         }  
  18.         return alertDiv;  
  19.     }  
  20. }   
Now let’s call this method from a controller which is saving records in the database. The following is the code snippet for the controller.
  1. // POST: EmployeeController/Create    
  2. [HttpPost]  
  3. [ValidateAntiForgeryToken]  
  4. public ActionResult Create([FromForm] EmployeeViewModel collection) {  
  5.     try {  
  6.         int result = 0;  
  7.         if (ModelState.IsValid) {  
  8.             Employee objEmp = new Employee();  
  9.             objEmp.EmpName = collection.EmpName;  
  10.             objEmp.Address = collection.Address;  
  11.             objEmp.Email = collection.Email;  
  12.             objEmp.Phone = collection.Phone;  
  13.             objEmp.BankAccountNo = collection.BankAccountNo;  
  14.             objEmp.CreatedOn = DateTime.Now;  
  15.             objEmp.CreatedBy = "SYSTEM";  
  16.             objEmp.ModifiedOn = null;  
  17.             objEmp.ModifiedBy = null;  
  18.             result = _empRepo.Add(objEmp).Result;  
  19.             //return RedirectToAction("Index");    
  20.             if (result > 0) {  
  21.                 ViewBag.Alert = CommonServices.ShowAlert(Alerts.Success, "Employee added");  
  22.             } else ViewBag.Alert = CommonServices.ShowAlert(Alerts.Danger, "Unknown error");  
  23.         }  
  24.         return PartialView("_Create");  
  25.     } catch {  
  26.         return View();  
  27.     }  
  28. }   
Code Explanation
  • In post type method we pass EmployeeViewModel class as a parameter as a model name that gets all data from the user.
  • _empRepo.Add() is a custom method used to save the Employee records. ( Repository Pattern is used to save a record here. You can download complete source code from the GitHub link given below ).
Step 4
 
Now add the below line in the view like this. It helps to render the HTML from the ViewBag string returned from the static method.
  1. @Html.Raw(@ViewBag.Alert)  
 
The following is the complete code snippet for the view.
  1. @model CodeSample.Models.EmployeeViewModel  
  2. @{  
  3.     ViewData["Title"] = "Add Employee";  
  4.     Layout = "~/Views/Shared/_Layout.cshtml";  
  5. }  
  6.   
  7. <h4>Add Employee</h4>  
  8. <hr />  
  9. <div class="row">     
  10.     <div class="col-md-4">  
  11.         <form asp-action="Create" asp-controller="Employee" method="post">  
  12.             <div asp-validation-summary="ModelOnly" class="text-danger"></div>  
  13.             <div class="form-group">  
  14.                 <label asp-for="EmpName" class="control-label">Enter employee name</label>  
  15.                 <input asp-for="EmpName" class="form-control" />  
  16.                 <span asp-validation-for="EmpName" class="text-danger"></span>  
  17.             </div>  
  18.             <div class="form-group">  
  19.                 <label asp-for="Email" class="control-label">Enter email</label>  
  20.                 <input asp-for="Email" class="form-control" />  
  21.                 <span asp-validation-for="Email" class="text-danger"></span>  
  22.             </div>  
  23.             <div class="form-group">  
  24.                 <label asp-for="Phone" class="control-label">Enter Phone No.</label>  
  25.                 <input asp-for="Phone" class="form-control" />  
  26.                 <span asp-validation-for="Phone" class="text-danger"></span>  
  27.             </div>  
  28.             <div class="form-group">  
  29.                 <label asp-for="Address" class="control-label">Enter Address</label>  
  30.                 <textarea asp-for="Address" class="form-control"></textarea>  
  31.                 <span asp-validation-for="Address" class="text-danger"></span>  
  32.             </div>  
  33.             <div class="form-group">  
  34.                 <label asp-for="BankAccountNo" class="control-label">Enter Bank Account No.</label>  
  35.                 <input asp-for="BankAccountNo" class="form-control" />  
  36.                 <span asp-validation-for="BankAccountNo" class="text-danger"></span>  
  37.             </div>  
  38.             <div class="form-group">  
  39.                 <input type="submit" id="SaveEmp" value="Create" class="btn btn-primary" />  
  40.             </div>  
  41.         </form>  
  42.     </div>  
  43.  </div>  
  44. <div class="row">  
  45.     <div class="col-md-12">  
  46.         <div class="form-group">  
  47.             @Html.Raw(@ViewBag.Alert)  
  48.         </div>  
  49.     </div>  
  50. </div>  
  51.   
  52.  <div><a asp-action="Index">Back to List</a></div>  
  53.   
  54.  @section Scripts {  
  55.   
  56.         @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}  
  57.  }  
Now if something goes wrong and the application is unable to insert the record in the database, it will show an error alert like this. 
 
 
Else it will show a success alert like this.
 
 

Summary

 
Here we saw how to display a bootstrap alert dynamically from ASP.NET Core 3.1 MVC Application. Hope you like this article and get some information from it.
 
Download Complete Code 
  • https://github.com/ArnabMSDN/ASP.NET-Core-Sample