Sweet Alert With MVC

Before this we were using traditional alert, what it is?. It is a JavaScript alert and now let’s replace it with Sweet Alert.

As you can see there are many articles of sweet alert but all are with html pages, none of them with MVC or ASP.NET. I had written simple article on this to understand easily and use it in your Projects.

sweet

Let’s start with creating basic MVC project first and then we are going add Sweet Alert inside it.

Creating Application

Open Visual Studio IDE on start page and select New Project.

Start page
                                                                           Figure 1: Start page

After selecting a New Project dialog will appear inside that select Templates Visual C# inside this select Web. After selecting you will see various Project Templates ( Webforms, MVC, ASP.NET AJAX Server control). In this select “ASP.NET MVC 4 Web Application” after selecting just name your Project as “SweetAlertSite” and finally click on OK button to create project.

Template
                                                                     Figure 2: Selecting Template

After clicking OK button another project template selection wizard will pop up with name “New ASP.NET MVC 4 Project”. In this template select Basic template and set view engine as Razor and we are not going to create Unit testing for this project hence do not check this option and finally click on OK button and done.

Project
                                    Figure 3: Selecting MVC 4 Project

After selecting all option as told above now click OK button and your project will be created.

structure
            Figure 4: Project structure

Installing Package SweetAlert to Project

After creating project we are going to add Sweet Alert for Bootstrap in our project. To install it from package manager console we are going to select Tools in Visual Studio IDE inside that we are going to select Library package manager and in that select package manager console and type
[ Install-Package SweetAlert ]

console
                                                         Figure 5: Package manager console

After successful installation it adds a Controller with name [SweetController] and View with name [Alert] with some css files in Content folder.

folder

Downloading package of bootstrap and adding to project

After installing Sweet alert we need to download and add bootstrap to project URL of it.

bootstrap
Figure 6: After adding bootstrap folder to project

After adding bootstrap to SweetAlertSite project now we are going to add Model in Models folder.

Adding Model (OrderFood)

For adding model in Solution Explorer just right click on Model folder and select Add, then inside that select class and then name class as OrderFood and finally click on Add button to create Model.

Model

Adding Property to (OrderFood) Model

After adding model let us add property to this Model.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.ComponentModel.DataAnnotations;  
  4. using System.Linq;  
  5. using System.Web;  
  6.   
  7. namespace SweetAlertSite.Models   
  8. {  
  9.     public class OrderFood  
  10.     {  
  11.         [Key]  
  12.         public int OrderID  
  13.         {  
  14.             get;  
  15.             set;  
  16.         }  
  17.         [Required(ErrorMessage = "Please enter OrderCode")]  
  18.         public string OrderCode  
  19.         {  
  20.             get;  
  21.             set;  
  22.         }  
  23.         [Required(ErrorMessage = "Please enter OrderPrice")]  
  24.         public string OrderPrice  
  25.         {  
  26.             get;  
  27.             set;  
  28.         }  
  29.   
  30.     }  
  31. }  
Adding (Home) Controller

To add controller just right click on Controller folder then select Add from list and inside that select controller.

controller
                                                Figure 7: Adding Controller (Home Controller)

After selecting controller a new dialog will pop up with name Add Controller.

Add

Now let’s name Controller to HomeController. In template we are going to select empty MVC controller. Finally, click on Add button to create HomeController. After adding HomeController you will see Index Action Method created by default.

Adding 2 New Action Method with Name Create to Home Controller

Let’s add 2 new Action with name and create one for POST and other for Get.
  1. using SweetAlertSite.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace SweetAlertSite.Controllers  
  9. {  
  10.     public class HomeController: Controller   
  11.     {  
  12.         //  
  13.         // GET: /Home/  
  14.   
  15.         public ActionResult Index()  
  16.         {  
  17.             return View();  
  18.         }  
  19.   
  20.   
  21.         [HttpGet]  
  22.         public ActionResult Create()  
  23.         {  
  24.             return View(new OrderFood());  
  25.         }  
  26.   
  27.         [HttpPost]  
  28.         public ActionResult Create(OrderFood OrderFood)   
  29.         {  
  30.             if (ModelState.IsValid)   
  31.             {  
  32.   
  33.             } else  
  34.             {  
  35.   
  36.             }  
  37.             return View(OrderFood);  
  38.         }  
  39.   
  40.     }  
  41. }  
After adding Action Method now let us add View to this Action Method.

Adding View for creating Action Method

For adding View just right click inside Controller Action Method (Create) then select option Add View.

Adding View
            Figure 8: Adding View (Create [Home Controller])

After selecting Add View option a new wizard will pop up with Name (Add View).

It will have View Name same name as Action Method inside which you right click to add View.

In this example we are going to create strongly typed view for that I have check this option and in Model class I have selected OrderFood model class.

After selecting required option now finally click on Add button.

After that a View will be created inside Views folder and in that we will have folder with name of controller inside that your view will be placed.

Create
   Figure 9: After adding Create View

Now let’s add script reference to this Page to use Sweet Alert.

Adding Script Reference to View (Create View)

alert
                                                         Figure 10: Scripts to add for using sweet alert.
  1. <script src="~/Scripts/jquery-1.11.3.min.js">  
  2. </script>  
  3.   
  4. <script src="~/Scripts/jquery.validate.min.js"></script>  
  5. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
  6.   
  7. <link href="~/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet" />  
  8. <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>  
  9.   
  10. <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>  
  11. <link href="~/Content/sweetalert/sweet-alert.css" rel="stylesheet" />  
After adding script now let’s add validation.

Adding Sweet Alert Simple alert Validation on Create View

We are going to validate 2 textbox they must not be blank - use sweet alert.

 Javascript alert Sweet alert
 diffrence diffrence
 alert("Please enter OrderCode !");  swal("Please enter OrderCode !");
 Alert starts with alert keyword.  Sweet Alert starts with Swal keyword.
                                          Figure 11: Different between Sweet alert and Javascript alert.

Code snippet of Sweet Alert Validation on Create View
  1. <script type="text/javascript">  
  2.     function validateData()  
  3. {  
  4.     
  5.         if ($("#OrderCode").val() == "")  
  6.         {  
  7.             swal("Please enter OrderCode !");  
  8.             return false;  
  9.         } else if ($("#OrderPrice").val() == "")  
  10.         {  
  11.             swal("Please enter OrderPrice !");  
  12.             return false;  
  13.         } else  
  14.         {  
  15.             return true;  
  16.         }  
  17.     }  
  18. </script>  
  19.   
  20. <input type="submit" onclick="return validateData();" value="Create" />  
Snapshot of Sweet Alert Validation on Create View

alert
                                 Figure 12: Sweet alert Error message.

Code snippet of Complete Create View

Here's the complete code snippet for it.
  1. @model SweetAlertSite.Models.OrderFood  
  2.   
  3. @ {  
  4.     Layout = null;  
  5. }  
  6.   
  7. < !DOCTYPE html >  
  8.     < html >  
  9.     < head >  
  10.     < meta name = "viewport"  
  11. content = "width=device-width" / >  
  12.     < title > Create < /title>  
  13.   
  14. < script src = "~/Scripts/jquery-1.11.3.min.js" > < /script>  
  15.   
  16. < script src = "~/Scripts/jquery.validate.min.js" > < /script> < script src = "~/Scripts/jquery.validate.unobtrusive.min.js" > < /script>  
  17.   
  18. < link href = "~/bootstrap-3.3.6-dist/css/bootstrap.min.css"  
  19. rel = "stylesheet" / >  
  20.     < script src = "~/bootstrap-3.3.6-dist/js/bootstrap.js" > < /script>  
  21.   
  22. < script src = "https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js" > < /script> < link href = "~/Content/sweetalert/sweet-alert.css"  
  23. rel = "stylesheet" / >  
  24.   
  25.     < script type = "text/javascript" >  
  26.     function validateData()  
  27.     {  
  28.         debugger;  
  29.         
  30.         if ($("#OrderCode").val() == "")  
  31.         {  
  32.             swal("Please enter OrderCode !");  
  33.             return false;  
  34.         } else if ($("#OrderPrice").val() == "")   
  35.         {  
  36.             swal("Please enter OrderPrice !");  
  37.             return false;  
  38.         } else   
  39.         {  
  40.             return true;  
  41.         }  
  42.     } < /script> < /head> < body >  
  43.     @using(Html.BeginForm())  
  44.     {  
  45.         @Html.ValidationSummary(true)  
  46.   
  47.         < fieldset >  
  48.             < legend > OrderFood < /legend> < div class = "editor-label" >  
  49.             @Html.LabelFor(model => model.OrderCode) < /div> < div class = "editor-field" >  
  50.             @Html.EditorFor(model => model.OrderCode)  
  51.         @Html.ValidationMessageFor(model => model.OrderCode) < /div> < div class = "editor-label" >  
  52.             @Html.LabelFor(model => model.OrderPrice) < /div> < div class = "editor-field" >  
  53.             @Html.EditorFor(model => model.OrderPrice)  
  54.         @Html.ValidationMessageFor(model => model.OrderPrice) < /div> < p >  
  55.             < input type = "submit"  
  56.         onclick = "return validateData();"  
  57.         value = "Create" / >  
  58.             < /p> < /fieldset>  
  59.     }  
  60.   
  61. < div >  
  62.     @Html.ActionLink("Back to List""Index") < /div> < /body> < /html>  
After adding simple Validation now let us learn how to add confirmation message in Sweet Alert.

Adding Sweet Alert Confirmation Validation

We have already done with simple sweet alert validations now let’s work on confirmation validation. We are going to call this Confirmation alert as user click on save button and going to ask do you want to save form and there will be 2 buttons [Save] and [Cancel]. If user click on Save then form will be submitted else it will cancel.

Adding (Confirmation) Controller

For adding Confirmation message let add another Controller for understanding with name “Confirmation Controller” and in this controller we are going to add 2 Action Method with same name Create.

Confirmation
                              Figure 13: Adding Confirmation Controller.

Adding View for Create Action Method

After adding Action method now let’s add View to this action methods in similar as we have added above.

For adding View just right click inside Controller Action Method (Create) and then select option Add View.

Confirmation Controller
         Figure 14: Adding View (Create) of Confirmation Controller

After selecting Add View option a new wizard will pop up with Name (Add View).

It will have View Name same (name ) as Action Method inside which you right click to add View.

In this example we are going to create strongly typed view for that I have check this option and in Model class I have selected OrderFood model class.

After selecting required option now finally click on Add button.

After that a View will be created inside Views folder and in that we will have a folder with name of controller inside that your view will be placed.

Adding Script Reference to View (Create View)
  1. <script src="~/Scripts/jquery-1.11.3.min.js"></script>  
  2.   
  3. <script src="~/Scripts/jquery.validate.min.js"></script>  
  4. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
  5.   
  6. <link href="~/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet" />  
  7. <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>  
  8.   
  9. <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>  
  10. <link href="~/Content/sweetalert/sweet-alert.css" rel="stylesheet" />  
After adding script now let’s add validation.

Adding Sweet Alert Confirmation Validation on Create View

This script will first ask “Do you want to save it?” then there are 2 buttons “Save” and “Cancel”. If you click on Save then it will be saved else cancelled.
  1. <script type="text/javascript">  
  2.     function validateData()  
  3. {  
  4.     
  5.         if ($("#OrderCode").val() == "")  
  6.         {  
  7.             swal("Please enter OrderCode !");  
  8.             return false;  
  9.         } else if ($("#OrderPrice").val() == "")   
  10.         {  
  11.             swal("Please enter OrderPrice !");  
  12.             return false;  
  13.         } else  
  14.         {  
  15.             return true;  
  16.         }  
  17.     }  
  18.   
  19.     function Validate(ctl, event)  
  20. {  
  21.         event.preventDefault();  
  22.         swal({  
  23.                 title: "Do you want to save it?",  
  24.                 text: "Please check Information before Submiting!",  
  25.                 type: "warning",  
  26.                 showCancelButton: true,  
  27.                 confirmButtonColor: "#DD6B55",  
  28.                 confirmButtonText: "Save",  
  29.                 cancelButtonText: "Cancel",  
  30.                 closeOnConfirm: false,  
  31.                 closeOnCancel: false  
  32.             },  
  33.             function(isConfirm)   
  34.              {  
  35.                 if (isConfirm)  
  36.                 {  
  37.                     if (validateData() == true)   
  38.                     {  
  39.                         $("#CreateForm").submit();  
  40.                     }  
  41.                 } else   
  42.                 {  
  43.                     swal("Cancelled""You have Cancelled Form Submission!""error");  
  44.                 }  
  45.             });  
  46.     }  
  47. </script>  
  48.   
  49. <input type="submit" id="btnCreate" onclick="Validate(this, event);" value="Create" />  
Snapshot of Sweet Alert Confirmation onClick of Create button

Snapshot
                                    Figure 15: Sweet Alert Confirmation onClick of Create button

Snapshot of Sweet Alert Confirmation on Cancellation

Confirmation alert
                                                         Figure 16: On Cancel of Confirmation alert

Code snippet of complete Create View of (Confirmation)
  1. @model SweetAlertSite.Models.OrderFood  
  2. @ {  
  3.     Layout = null;  
  4. } < !DOCTYPE html >  
  5.     < html >  
  6.     < head >  
  7.     < meta name = "viewport"  
  8. content = "width=device-width" / >  
  9.     < title > Create < /title> < script src = "~/Scripts/jquery-1.11.3.min.js" > < /script> < script src = "~/Scripts/jquery.validate.min.js" > < /script> < script src = "~/Scripts/jquery.validate.unobtrusive.min.js" > < /script> < link href = "~/bootstrap-3.3.6-dist/css/bootstrap.min.css"  
  10. rel = "stylesheet" / >  
  11.     < script src = "~/bootstrap-3.3.6-dist/js/bootstrap.js" > < /script> < script src = "~/Scripts/sweet-alert.js" > < /script> < link href = "~/Content/sweetalert/sweet-alert.css"  
  12. rel = "stylesheet" / >  
  13.     < script type = "text/javascript" >  
  14.   
  15.     function validateData()   
  16.     {  
  17.         if ($("#OrderCode").val() == "")  
  18.         {  
  19.             swal("Please enter OrderCode !");  
  20.             return false;  
  21.         } else if ($("#OrderPrice").val() == "")   
  22.         {  
  23.             swal("Please enter OrderPrice !");  
  24.             return false;  
  25.         } else {  
  26.             return true;  
  27.         }  
  28.     }  
  29.   
  30. function Validate(ctl, event)  
  31. {  
  32.     event.preventDefault();  
  33.     swal({  
  34.             title: "Do you want to save it?",  
  35.             text: "Please check Information before Submiting!",  
  36.             type: "warning",  
  37.             showCancelButton: true,  
  38.             confirmButtonColor: "#DD6B55",  
  39.             confirmButtonText: "Save",  
  40.             cancelButtonText: "Cancel",  
  41.             closeOnConfirm: false,  
  42.             closeOnCancel: false  
  43.         },  
  44.         function(isConfirm)  
  45.          {  
  46.             if (isConfirm)  
  47.             {  
  48.                 if (validateData() == true)   
  49.                 {  
  50.                     $("#CreateForm").submit();  
  51.                 }  
  52.             } else {  
  53.                 swal("Cancelled""You have Cancelled Form Submission!""error");  
  54.             }  
  55.         });  
  56. } < /script> < /head> < body >  
  57.     @using(Html.BeginForm(nullnull, FormMethod.Post, new  
  58.     {  
  59.         id = "CreateForm"  
  60.     })) {  
  61.         @Html.ValidationSummary(true) < fieldset >  
  62.             < legend > OrderFood < /legend>  < div class = "editor-label" >  
  63.             @Html.LabelFor(model => model.OrderCode) < /div> < div class = "editor-field" >  
  64.             @Html.EditorFor(model => model.OrderCode)  
  65.         @Html.ValidationMessageFor(model => model.OrderCode) < /div> < div class = "editor-label" >  
  66.             @Html.LabelFor(model => model.OrderPrice) < /div> < div class = "editor-field" >  
  67.             @Html.EditorFor(model => model.OrderPrice)  
  68.         @Html.ValidationMessageFor(model => model.OrderPrice) < /div>  < p >  
  69.             < input type = "submit"  
  70.         id = "btnCreate"  
  71.         onclick = "Validate(this, event);"  
  72.         value = "Create" / >  
  73.             < /p> < /fieldset>  
  74.     } < /body> < /html>  
Adding (DeleteConfirmation) Controller

To add controller just right click on Controller folder then select Add from list and inside that select controller. After selecting controller a new dialog will pop up with name Add Controller.

Adding
               Figure 17: Adding DeleteConfirmationController

After adding Controller we are going to add 2 Action Method in this controller one will return View with List and other will return JSON result.

Code snippet of DeleteConfirmation Controller
  1. using SweetAlertSite.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7.   
  8. namespace SweetAlertSite.Controllers  
  9. {  
  10.     public class DeleteConfirmation: Controller  
  11.     {  
  12.   
  13.         [HttpGet]  
  14.         public ActionResult Details()  
  15.         {  
  16.             List < OrderFood > listor = new List < OrderFood > ();  
  17.   
  18.             OrderFood OF = new OrderFood();  
  19.             OF.OrderID = 1;  
  20.             OF.OrderCode = "0001";  
  21.             OF.OrderPrice = "1000";  
  22.   
  23.             OrderFood OF1 = new OrderFood();  
  24.             OF1.OrderID = 2;  
  25.             OF1.OrderCode = "0002";  
  26.             OF1.OrderPrice = "2000";  
  27.   
  28.             listor.Add(OF);  
  29.             listor.Add(OF1);  
  30.   
  31.             return View(listor);  
  32.         }  
  33.   
  34.         public ActionResult delete(string OrderID) {  
  35.             return Json("delete", JsonRequestBehavior.AllowGet);  
  36.         }  
  37.     }  
  38. }  
Code snippet of DeleteConfirmation Controller

After adding Action Method now we are going to add View to this Action Method (Details).

For adding View just right click inside Controller Action Method (Create) and then select option Add View.

Details
Figure 18: Adding View with name Details [DeleteConfirmationController]

After selecting Add View option a new wizard will pop up with Name (Add View).

In Scaffold template I have selected List because we are going to show list of order from that you can delete if you don’t want any.

It will have View Name same name as Action Method inside which you right click to add View.

In this example we are going to create strongly typed view for that I have checked this option and in Model class I have selected OrderFood model class.

After selecting required option now finally click on Add button.

After that a View will be created inside Views folder and in that we will have a folder with name of controller inside that your view will be placed.

Making changes in View removing link button and adding single button for Delete

We have added a List page here it will show all order records.

Details
                        Figure 19: View Details [DeleteConfirmationController]

From Details View we are going to remove this link button and going to add a single button here.

Details
   Figure 20: View Details after removing action links and adding single delete button

After adding button now we are going to add Scripts Reference.

Adding Script Reference to View (Details View)
  1. <script src="~/Scripts/jquery-1.11.3.min.js"></script>  
  2.   
  3. <script src="~/Scripts/jquery.validate.min.js"></script>  
  4. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
  5.   
  6. <link href="~/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet" />  
  7. <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>  
  8.   
  9. <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>  
  10. <link href="~/Content/sweetalert/sweet-alert.css" rel="stylesheet" />  
After adding Script now let’s add validation

This script will first ask “Are you sure that you want to delete this Order?”, then there are 2 buttons “Delete” and “Cancel”. If you click on Delete button then it will delete record using Ajax Post request else if you have clicked on Cancel button then it do not perform any thing. 
  1. It will show dialog of confirmation.
  2. If you click on delete button then it will perform Ajax Post event with this URL [/DeleteConfirmation/delete/] and pass OrderID to It for deleting record. After that it will call [window.location.href = '/DeleteConfirmation/Details'] ( to refresh this page ).
    1. <script type="text/javascript">  
    2.     function deleteOrder(OrderID)  
    3. {  
    4.         debugger;  
    5.         swal({  
    6.                 title: "Are you sure?",  
    7.                 text: "Are you sure that you want to delete this Order?",  
    8.                 type: "warning",  
    9.                 showCancelButton: true,  
    10.                 closeOnConfirm: false,  
    11.                 confirmButtonText: "Yes, delete it!",  
    12.                 confirmButtonColor: "#ec6c62"  
    13.             },  
    14.             function()   
    15.              {  
    16.                 $.ajax({  
    17.                         url: "/DeleteConfirmation/delete/",  
    18.                         data:  
    19.                   {  
    20.                             "OrderID": OrderID  
    21.                         },  
    22.                         type: "DELETE"  
    23.                     })  
    24.                     .done(function(data)   
    25.                           {  
    26.                         sweetAlert  
    27.                             ({  
    28.                                     title: "Deleted!",  
    29.                                     text: "Your file was successfully deleted!",  
    30.                                     type: "success"  
    31.                                 },  
    32.                                 function()  
    33.                              {  
    34.                                     window.location.href = '/DeleteConfirmation/Details';  
    35.                                 });  
    36.                     })  
    37.                     .error(function(data)  
    38.                       {  
    39.                         swal("Oops""We couldn't connect to the server!""error");  
    40.                     });  
    41.             });  
    42.     }  
    43. </script>  

Snapshot of Sweet Alert DeleteConfirmation onClick of Delete button

deleting
                                                            Figure 21: Confirmation while deleting records

deleting
                                                               Figure 22: Message after deleting record

Code snippet of Details View

  1. @model IEnumerable < SweetAlertSite.Models.OrderFood >  
  2.   
  3.     @ {  
  4.         Layout = null;  
  5.     }  
  6.   
  7. < !DOCTYPE html >  
  8.   
  9.     < html >  
  10.     < head >  
  11.     < meta name = "viewport"  
  12. content = "width=device-width" / >  
  13.     < title > Details < /title>  
  14.   
  15. < script src = "~/Scripts/jquery-1.11.3.min.js" > < /script> < script src = "~/Scripts/jquery.validate.min.js" > < /script> < script src = "~/Scripts/jquery.validate.unobtrusive.min.js" > < /script> < link href = "~/bootstrap-3.3.6-dist/css/bootstrap.min.css"  
  16. rel = "stylesheet" / >  
  17.     < script src = "~/bootstrap-3.3.6-dist/js/bootstrap.js" > < /script> < script src = "https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js" > < /script>  
  18.   
  19. < link href = "~/Content/sweetalert/sweet-alert.css"  
  20. rel = "stylesheet" / >  
  21.   
  22.     < script type = "text/javascript" >  
  23.     function deleteOrder(OrderID)  
  24.     {  
  25.         debugger;  
  26.         swal({  
  27.                 title: "Are you sure?",  
  28.                 text: "Are you sure that you want to delete this Order?",  
  29.                 type: "warning",  
  30.                 showCancelButton: true,  
  31.                 closeOnConfirm: false,  
  32.                 confirmButtonClass: "btn-danger",  
  33.                 confirmButtonText: "Delete",  
  34.                 confirmButtonColor: "#ec6c62"  
  35.             },  
  36.             function()  
  37.              {  
  38.                 $.ajax({  
  39.                         url: "/DeleteConfirmation/delete/",  
  40.                         data:  
  41.                   {  
  42.                             "OrderID": OrderID  
  43.                         },  
  44.                         type: "DELETE"  
  45.                     })  
  46.                     .done(function(data)   
  47.                           {  
  48.                         sweetAlert  
  49.                             ({  
  50.                                     title: "Deleted!",  
  51.                                     text: "Your file was successfully deleted!",  
  52.                                     type: "success"  
  53.                                 },  
  54.                                 function()   
  55.                              {  
  56.                                     window.location.href = '/DeleteConfirmation/Details';  
  57.                                 });  
  58.                     })  
  59.                     .error(function(data)  
  60.                      {  
  61.                         swal("Oops""We couldn't connect to the server!""error");  
  62.                     });  
  63.             });  
  64.     } < /script>  
  65.   
  66.   
  67. < /head> < body >  
  68.     < p style = "text-align:left" >  
  69.     Delete Order < /p> < table style = "margin-left:20px;" >  
  70.     < tr >  
  71.     < th style = "text-align:center" >  
  72.     @Html.DisplayNameFor(model => model.OrderCode) |  
  73.     < /th>  < th style = "text-align:center" >  
  74.     @Html.DisplayNameFor(model => model.OrderPrice) |  
  75.     < /th>  < th > Action < /th> < /tr>   
  76. @foreach(var item in Model) { < tr >  
  77.         < td style = "text-align:center" >  
  78.         @Html.DisplayFor(modelItem => item.OrderCode) < /td> < td style = "text-align:center" >  
  79.         @Html.DisplayFor(modelItem => item.OrderPrice) < /td> < td style = "text-align:center" >  
  80.         < input id = "Delete"  
  81.     onclick = "deleteOrder('@item.OrderID')"  
  82.     type = "button"  
  83.     value = "Delete" / >  
  84.         < /td> < /tr>  
  85. } < /table> < /body> < /html>  
Finally, we are going to see how to show message after saving records.

Displaying success message after saving record

I have made small change in HttpPost request of create action Method of home controller.

If data submitted is valid then I am going to show message. For that I have stored a message in TempData to display. After this I am redirecting request to Http Get request of create action Method of home controller.
  1. [HttpGet]  
  2. public ActionResult Create()   
  3. {  
  4.     return View(new OrderFood());  
  5. }  
  6.   
  7. [HttpPost]  
  8. public ActionResult Create(OrderFood OrderFood)  
  9. {  
  10.     if (ModelState.IsValid)   
  11.     {  
  12.         TempData["Message"] = "Your Order " + OrderFood.OrderCode + "has been Saved Successfully ";  
  13.         return RedirectToAction("Create");  
  14.     } else  
  15.     {  
  16.   
  17.     }  
  18.     return View(OrderFood);  
  19. }  
Code snippet of Create View [Home Controller]

In this code snippet of Create View of home controller I am going to check that TempData["Message"] is Not null if it is not null then I am going to show message which is stored in TempData using Sweet Alert.
  1. <script src="~/Scripts/jquery-1.11.3.min.js"></script>  
  2.   
  3. <script src="~/Scripts/jquery.validate.min.js"></script>  
  4. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>  
  5.   
  6. <link href="~/bootstrap-3.3.6-dist/css/bootstrap.min.css" rel="stylesheet" />  
  7. <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>  
  8.   
  9. <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>  
  10. <link href="~/Content/sweetalert/sweet-alert.css" rel="stylesheet" />  
  11.   
  12. <script type="text/javascript">  
  13.     @if(TempData["Message"] != null) { < text >  
  14.             $(window).load(function()  
  15.                 {  
  16.                 $(document).ready(function()  
  17.                     {  
  18.                     swal({  
  19.                         title: "Message",  
  20.                         text: "@TempData["  
  21.                         Message "]",  
  22.                         type: "success"  
  23.                     });  
  24.                 });  
  25.             }); < /text>  
  26.     }  
  27. </script>  
Snapshot of Sweet Alert on Saving Record

Message
                                                               Figure 23: Message after saving record

Finally, we completed using Sweet Alert with MVC. I like this message and I know you too will like it.

Tips:

We were using this link
  1. <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>   
You can download sweet-alert.js from this link and add to your project.

Some people had issue with copying text with Sweet Alert they can resolve issue by the following steps given below.

Find [ window.sweetAlertInitialize ] in sweet-alert.js file.

Then find [ tabIndex=-1 ] and Remove it.

Finally, save your file now it works. For reference visit this site.


Similar Articles