Introduction To Sweet Alert Library In ASP.NET MVC Razor

Introduction

Sweet Alert is a library that acts as a replacement for the JavaScript’s alert() function. This shows very pretty model windows. It’s a library that has no dependencies, and is made from a JavaScript file plus a CSS file. This library comes in three different flavors -

The first is a library that you can use in any web project; the second is a fork that is specifically adapted to work with Bootstrap; and
the third is a fork that you can use in your Android projects.

How to get Sweet Alert JavaScript File

To use Sweet Alert in your projects, you have to download it and include it in the pages where you intend to use this library. Also, I have added Sweet Alert related CSS and JavaScript file.
  1. sweetalert.css
  2. sweetalert.js
  3. sweetalert.min.js
The library operates through a method called sweetAlert. It accepts up to three parameters.
  1. title (mandatory): A string representing the title of the alert shown.
  2. message (optional): An optional string representing the message shown beneath the title.
  3. type(optional): An optional string representing the type of message you want to show. Its value may be one of "success", "error", "warning", and "info".
The library also offers a nice shortcut to invoke the sweetAlert method called swal.
  1. sweetAlert("File Shouldn't Be Empty!!""Please select file""error"); 
Description

The first option I want to cover allows you to change the text of the buttons shown. For example, if you want to change the text of the button for the success message from “OK” to “Yeah!”, you can set the value for an option called confirmButtonText. If you want to change the text of the button for the Cancel button, you have to set the value of cancelButtonText. At this point, the most observant of you should raise up the hand and say “I haven’t seen any cancel button so far, what are you talking about?” If you did, excellent!

The truth is that Sweet Alert allows you to show a Cancel message but you have to explicitly specify that you want it. You can do that by setting the option showCancelButton to true.

  1. swal({  
  2.    title: 'Confirm',  
  3.    text: 'Are you sure to delete this message?',  
  4.    type: 'warning',  
  5.    showCancelButton: true,  
  6.    confirmButtonText: 'Yes, sir',  
  7.    cancelButtonText: 'Not at all'  
  8. }); 
In case you don’t like the colors of the confirm button, you can also change it by setting a hash value for the confirmButtonColor option.

Another interesting option is that you can set that a message is displayed for a fixed amount of time and then is auto-closed. You can achieve this task by passing a number, representing the number of milliseconds after which the message is closed to an option called timer. The following code uses these other two options.
  1. swal({  
  2.    title: 'Confirm',  
  3.    text: 'Are you sure to delete this message?',  
  4.    type: 'warning',  
  5.    showCancelButton: true,  
  6.    confirmButtonColor: '#987463',  
  7.    timer: 1500  
  8. }); 
That allows you to show a very nice messages to your users. This library works on any type of device, so you can employ it in your responsive website too.

Steps to be followed

Step 1

Create an MVC application named "ExceluploadDB".
 
Step 2

Create a Controller class file named "ExcelUploadController.cs".
 
Code Ref
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace ExceluploadDB.Controllers  
  8. {  
  9.     public class ExcelUploadController : Controller  
  10.     {  
  11.         public ActionResult ExcelUpload()  
  12.         {  
  13.             return View();  
  14.         }  
  15.     }  

Step 3

Add 3 Sweet Alert related CSS and JavaScript files in the Scripts folder.
  1. sweetalert.css
  2. sweetalert.js
  3. sweetalert.min.js 
 
 
Step 4

Create a View file named "ExcelUpload.cshtml".

 
Code Ref
  1. @{  
  2.     ViewBag.Title = "Satyaprakash Sweetalert Javascript File";  
  3. }  
  4.   
  5. <br />  
  6. <div align="center">  
  7.     @if (ViewBag.Message != null)  
  8.     {  
  9.         <span class="success sweet-alert"> @ViewBag.Message</span>  
  10.     }  
  11.     <br />  
  12.     <div align="right" class="btn btn-default">  
  13.         @using (Html.BeginForm("UploadExcel""ExcelUpload", FormMethod.Post, new { @enctype = "multipart/form-data" }))  
  14.         {  
  15.             <input type="file" id="fileUpload" class="btn btn-primary" name="FileUpload" /><br />  
  16.             <input type="submit" class="btn btn-primary" name="UploadNewEmployee" id="fileUploadExcel" value="POST" />  
  17.         }  
  18.     </div>  
  19.   
  20.   
  21. </div>  
  22. <link href="~/Scripts/sweetalert.css" rel="stylesheet" />  
  23. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  24. <script src="~/Scripts/sweetalert.js"></script>  
  25. <script>  
  26.   
  27.     $('#fileUploadExcel').click(function (e) {  
  28.         if ($('#fileUpload').val() === "") {  
  29.             sweetAlert("File Shouldn't Be Empty!!""Please select file""error");  
  30.             //alert("File Shouldn't Be Empty!!");  
  31.             return false;  
  32.         }  
  33.         if ($('#fileUpload').val() !== "") {  
  34.             sweetAlert("Congratulations!!""You Uploaded A Valid File""success");  
  35.             return false;  
  36.         }  
  37.     });  
  38.   
  39. </script> 
Code Decsription

Here, I have added a title of the browser. 
  1. @{  
  2.     ViewBag.Title = "Satyaprakash Sweetalert Javascript File";  

Here, if the file is successfully uploaded to server/destination, the success message will show up.
  1. @if (ViewBag.Message != null)  
  2.     {  
  3.         <span class="success sweet-alert"> @ViewBag.Message</span>  
  4.     } 
Then, I ahae added an upload control and a button inside the BeginForm HTML helper control.

BeginForm 

When the user submits the form, the request will be processed by an action method.
  1. @using (Html.BeginForm("UploadExcel""ExcelUpload", FormMethod.Post, new { @enctype = "multipart/form-data" }))  
  2.         {  
  3.             <input type="file" id="fileUpload" class="btn btn-primary" name="FileUpload" /><br />  
  4.             <input type="submit" class="btn btn-primary" name="UploadNewEmployee" id="fileUploadExcel" value="POST" />  
  5.         } 
Then, I have added references to sweetalert files.
  1. <link href="~/Scripts/sweetalert.css" rel="stylesheet" />  
  2. <script src="~/Scripts/jquery-1.10.2.js"></script>  
  3. <script src="~/Scripts/sweetalert.js"></script> 
Next, put condition for if upload contol is empty and not empty, then the alert message will be shown to the end user when user clicked on the button.
  1. $('#fileUploadExcel').click(function (e) {  
  2.         if ($('#fileUpload').val() === "") {  
  3.             sweetAlert("File Shouldn't Be Empty!!""Please select file""error");  
  4.             //alert("File Shouldn't Be Empty!!");  
  5.             return false;  
  6.         }  
  7.         if ($('#fileUpload').val() !== "") {  
  8.             sweetAlert("Congratulations!!""You Uploaded A Valid File""success");  
  9.             return false;  
  10.         }  
  11.     }); 
Difference between Normal alert and SweetAlert JavaScript library.
  1. $('#fileUploadExcel').click(function (e) {  
  2.        if ($('#fileUpload').val() === "") {  
  3.            alert("File Shouldn't Be Empty!!");  
  4.            return false;  
  5.        }  
  6.   
  7. $('#fileUploadExcel').click(function (e) {  
  8.        if ($('#fileUpload').val() === "") {  
  9.            sweetAlert("File Shouldn't Be Empty!!""Please select file""error");  
  10.            return false;  
  11.        } 
Step 5

Then, customize the layout file named "~/Views/Shared/_Layout.cshtml".

Code Ref
  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">  
  6.     <title>@ViewBag.Title</title>  
  7.     @Styles.Render("~/Content/css")  
  8.     @Scripts.Render("~/bundles/modernizr")  
  9.   
  10. </head>  
  11. <body>  
  12.     <div class="navbar navbar-inverse navbar-fixed-top">  
  13.         <div class="container">  
  14.             <div class="navbar-header">  
  15.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  16.                     <span class="icon-bar"></span>  
  17.                     <span class="icon-bar"></span>  
  18.                     <span class="icon-bar"></span>  
  19.                 </button>  
  20.                 @*@Html.ActionLink("Application name""Index""Home"nullnew { @class = "navbar-brand" })*@  
  21.             </div>  
  22.             <div class="navbar-collapse collapse">  
  23.                 <ul class="nav navbar-nav">  
  24.                     @*<li>@Html.ActionLink("Satyaprakash Samantaray""ExcelUpload""ExcelUpload")</li>*@  
  25.                     <h2 style="color: white;text-align: center; font-style: oblique">Satyaprakash's Sweet Alert</h2>   
  26.                     @*<li>@Html.ActionLink("About""About""Home")</li>  
  27.                     <li>@Html.ActionLink("Contact""Contact""Home")</li>*@  
  28.                 </ul>  
  29.                 @*@Html.Partial("_LoginPartial")*@  
  30.             </div>  
  31.         </div>  
  32.     </div>  
  33.     <div class="container body-content">  
  34.         @RenderBody()  
  35.         @*<hr />*@  
  36.         <footer>  
  37.             @*<p>© @DateTime.Now.Hour - Satyaprakash Samantaray</p>*@  
  38.         </footer>  
  39.     </div>  
  40.   
  41.     @Scripts.Render("~/bundles/jquery")  
  42.     @Scripts.Render("~/bundles/bootstrap")  
  43.     @RenderSection("scripts", required: false)  
  44. </body>  
  45. </html> 
 
 
OUTPUT

DESKTOP VIEW (If file is empty)

 


DESKTOP VIEW (If file is not empty).



MOBILE VIEW



Difference between normal alert and Sweet Alert JavaScript library.

For Normal Alert



For Sweet Alert



Summary
 
We learned here about the following -
  1. What is Sweet Alert?
  2. Difference between Normal alert and Sweet Alert.
  3. Sweet Alert supports multi-platform enviornment.
  4. Resources required to implement Sweet Alert.

Up Next
    Ebook Download
    View all
    Learn
    View all