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.
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.
Figure 1: Start page
After selecting a New Project dialog will appear inside that select Templates Visual C# inside this select Web. Aafter 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.
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.
Figure 3: Selecting MVC 4 Project
After selecting all option as told above now click OK button and your project will be created.
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 ]
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.
Downloading package of bootstrap and adding to project
After installing Sweet alert we need to download and add bootstrap to project URL of it.
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.
Adding Property to (OrderFood) Model
After adding model let us add property to this Model.
- using System;
- using System.Collections.Generic;
- using System.ComponentModel.DataAnnotations;
- using System.Linq;
- using System.Web;
-
- namespace SweetAlertSite.Models
- {
- public class OrderFood
- {
- [Key]
- public int OrderID
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Please enter OrderCode")]
- public string OrderCode
- {
- get;
- set;
- }
- [Required(ErrorMessage = "Please enter OrderPrice")]
- public string OrderPrice
- {
- get;
- set;
- }
-
- }
- }
Adding (Home) Controller
To add controller just right click on
Controller folder then select Add from list and inside that select controller.
Figure 7: Adding Controller (Home Controller)
After selecting controller a new dialog will pop up with name
Add Controller.
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.
- using SweetAlertSite.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace SweetAlertSite.Controllers
- {
- public class HomeController: Controller
- {
-
-
-
- public ActionResult Index()
- {
- return View();
- }
-
-
- [HttpGet]
- public ActionResult Create()
- {
- return View(new OrderFood());
- }
-
- [HttpPost]
- public ActionResult Create(OrderFood OrderFood)
- {
- if (ModelState.IsValid)
- {
-
- } else
- {
-
- }
- return View(OrderFood);
- }
-
- }
- }
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.
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.
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)
Figure 10: Scripts to add for using sweet alert.
- <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" rel="stylesheet" />
- <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>
-
- <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>
- <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 |
| |
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
- <script type="text/javascript">
- function validateData()
- {
-
- if ($("#OrderCode").val() == "")
- {
- swal("Please enter OrderCode !");
- return false;
- } else if ($("#OrderPrice").val() == "")
- {
- swal("Please enter OrderPrice !");
- return false;
- } else
- {
- return true;
- }
- }
- </script>
-
- <input type="submit" onclick="return validateData();" value="Create" />
Snapshot of Sweet Alert Validation on Create View
Figure 12: Sweet alert Error message.
Code snippet of Complete Create View
Here's the complete code snippet for it.
- @model SweetAlertSite.Models.OrderFood
-
- @ {
- Layout = null;
- }
-
- < !DOCTYPE html >
- < html >
- < head >
- < meta name = "viewport"
- content = "width=device-width" / >
- < 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"
- rel = "stylesheet" / >
- < script src = "~/bootstrap-3.3.6-dist/js/bootstrap.js" > < /script>
-
- < script src = "https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js" > < /script> < link href = "~/Content/sweetalert/sweet-alert.css"
- rel = "stylesheet" / >
-
- < script type = "text/javascript" >
- function validateData()
- {
- debugger;
-
- if ($("#OrderCode").val() == "")
- {
- swal("Please enter OrderCode !");
- return false;
- } else if ($("#OrderPrice").val() == "")
- {
- swal("Please enter OrderPrice !");
- return false;
- } else
- {
- return true;
- }
- } < /script> < /head> < body >
- @using(Html.BeginForm())
- {
- @Html.ValidationSummary(true)
-
- < fieldset >
- < legend > OrderFood < /legend> < div class = "editor-label" >
- @Html.LabelFor(model => model.OrderCode) < /div> < div class = "editor-field" >
- @Html.EditorFor(model => model.OrderCode)
- @Html.ValidationMessageFor(model => model.OrderCode) < /div> < div class = "editor-label" >
- @Html.LabelFor(model => model.OrderPrice) < /div> < div class = "editor-field" >
- @Html.EditorFor(model => model.OrderPrice)
- @Html.ValidationMessageFor(model => model.OrderPrice) < /div> < p >
- < input type = "submit"
- onclick = "return validateData();"
- value = "Create" / >
- < /p> < /fieldset>
- }
-
- < div >
- @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.
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.
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)
- <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" rel="stylesheet" />
- <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>
-
- <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>
- <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.
- <script type="text/javascript">
- function validateData()
- {
-
- if ($("#OrderCode").val() == "")
- {
- swal("Please enter OrderCode !");
- return false;
- } else if ($("#OrderPrice").val() == "")
- {
- swal("Please enter OrderPrice !");
- return false;
- } else
- {
- return true;
- }
- }
-
- function Validate(ctl, event)
- {
- event.preventDefault();
- swal({
- title: "Do you want to save it?",
- text: "Please check Information before Submiting!",
- type: "warning",
- showCancelButton: true,
- confirmButtonColor: "#DD6B55",
- confirmButtonText: "Save",
- cancelButtonText: "Cancel",
- closeOnConfirm: false,
- closeOnCancel: false
- },
- function(isConfirm)
- {
- if (isConfirm)
- {
- if (validateData() == true)
- {
- $("#CreateForm").submit();
- }
- } else
- {
- swal("Cancelled", "You have Cancelled Form Submission!", "error");
- }
- });
- }
- </script>
-
- <input type="submit" id="btnCreate" onclick="Validate(this, event);" value="Create" />
Snapshot of Sweet Alert Confirmation onClick of Create button
Figure 15: Sweet Alert Confirmation onClick of Create button
Snapshot of Sweet Alert Confirmation on Cancellation
Figure 16: On Cancel of Confirmation alert
Code snippet of complete Create View of (Confirmation)
- @model SweetAlertSite.Models.OrderFood
- @ {
- Layout = null;
- } < !DOCTYPE html >
- < html >
- < head >
- < meta name = "viewport"
- content = "width=device-width" / >
- < 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"
- rel = "stylesheet" / >
- < 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"
- rel = "stylesheet" / >
- < script type = "text/javascript" >
-
- function validateData()
- {
- if ($("#OrderCode").val() == "")
- {
- swal("Please enter OrderCode !");
- return false;
- } else if ($("#OrderPrice").val() == "")
- {
- swal("Please enter OrderPrice !");
- return false;
- } else {
- return true;
- }
- }
-
- function Validate(ctl, event)
- {
- event.preventDefault();
- swal({
- title: "Do you want to save it?",
- text: "Please check Information before Submiting!",
- type: "warning",
- showCancelButton: true,
- confirmButtonColor: "#DD6B55",
- confirmButtonText: "Save",
- cancelButtonText: "Cancel",
- closeOnConfirm: false,
- closeOnCancel: false
- },
- function(isConfirm)
- {
- if (isConfirm)
- {
- if (validateData() == true)
- {
- $("#CreateForm").submit();
- }
- } else {
- swal("Cancelled", "You have Cancelled Form Submission!", "error");
- }
- });
- } < /script> < /head> < body >
- @using(Html.BeginForm(null, null, FormMethod.Post, new
- {
- id = "CreateForm"
- })) {
- @Html.ValidationSummary(true) < fieldset >
- < legend > OrderFood < /legend> < div class = "editor-label" >
- @Html.LabelFor(model => model.OrderCode) < /div> < div class = "editor-field" >
- @Html.EditorFor(model => model.OrderCode)
- @Html.ValidationMessageFor(model => model.OrderCode) < /div> < div class = "editor-label" >
- @Html.LabelFor(model => model.OrderPrice) < /div> < div class = "editor-field" >
- @Html.EditorFor(model => model.OrderPrice)
- @Html.ValidationMessageFor(model => model.OrderPrice) < /div> < p >
- < input type = "submit"
- id = "btnCreate"
- onclick = "Validate(this, event);"
- value = "Create" / >
- < /p> < /fieldset>
- } < /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.
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
- using SweetAlertSite.Models;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace SweetAlertSite.Controllers
- {
- public class DeleteConfirmation: Controller
- {
-
- [HttpGet]
- public ActionResult Details()
- {
- List < OrderFood > listor = new List < OrderFood > ();
-
- OrderFood OF = new OrderFood();
- OF.OrderID = 1;
- OF.OrderCode = "0001";
- OF.OrderPrice = "1000";
-
- OrderFood OF1 = new OrderFood();
- OF1.OrderID = 2;
- OF1.OrderCode = "0002";
- OF1.OrderPrice = "2000";
-
- listor.Add(OF);
- listor.Add(OF1);
-
- return View(listor);
- }
-
- public ActionResult delete(string OrderID) {
- return Json("delete", JsonRequestBehavior.AllowGet);
- }
- }
- }
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.
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.
Figure 19: View Details [DeleteConfirmationController]
From Details View we are going to remove this link button and going to add a single button here.
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)
- <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" rel="stylesheet" />
- <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>
-
- <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>
- <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.
- It will show dialog of confirmation.
- 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 ).
- <script type="text/javascript">
- function deleteOrder(OrderID)
- {
- debugger;
- swal({
- title: "Are you sure?",
- text: "Are you sure that you want to delete this Order?",
- type: "warning",
- showCancelButton: true,
- closeOnConfirm: false,
- confirmButtonText: "Yes, delete it!",
- confirmButtonColor: "#ec6c62"
- },
- function()
- {
- $.ajax({
- url: "/DeleteConfirmation/delete/",
- data:
- {
- "OrderID": OrderID
- },
- type: "DELETE"
- })
- .done(function(data)
- {
- sweetAlert
- ({
- title: "Deleted!",
- text: "Your file was successfully deleted!",
- type: "success"
- },
- function()
- {
- window.location.href = '/DeleteConfirmation/Details';
- });
- })
- .error(function(data)
- {
- swal("Oops", "We couldn't connect to the server!", "error");
- });
- });
- }
- </script>
Snapshot of Sweet Alert DeleteConfirmation onClick of Delete button
Figure 21: Confirmation while deleting records
Figure 22: Message after deleting record
Code snippet of Details View
- @model IEnumerable < SweetAlertSite.Models.OrderFood >
-
- @ {
- Layout = null;
- }
-
- < !DOCTYPE html >
-
- < html >
- < head >
- < meta name = "viewport"
- content = "width=device-width" / >
- < title > Details < /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"
- rel = "stylesheet" / >
- < script src = "~/bootstrap-3.3.6-dist/js/bootstrap.js" > < /script> < script src = "https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js" > < /script>
-
- < link href = "~/Content/sweetalert/sweet-alert.css"
- rel = "stylesheet" / >
-
- < script type = "text/javascript" >
- function deleteOrder(OrderID)
- {
- debugger;
- swal({
- title: "Are you sure?",
- text: "Are you sure that you want to delete this Order?",
- type: "warning",
- showCancelButton: true,
- closeOnConfirm: false,
- confirmButtonClass: "btn-danger",
- confirmButtonText: "Delete",
- confirmButtonColor: "#ec6c62"
- },
- function()
- {
- $.ajax({
- url: "/DeleteConfirmation/delete/",
- data:
- {
- "OrderID": OrderID
- },
- type: "DELETE"
- })
- .done(function(data)
- {
- sweetAlert
- ({
- title: "Deleted!",
- text: "Your file was successfully deleted!",
- type: "success"
- },
- function()
- {
- window.location.href = '/DeleteConfirmation/Details';
- });
- })
- .error(function(data)
- {
- swal("Oops", "We couldn't connect to the server!", "error");
- });
- });
- } < /script>
-
-
- < /head> < body >
- < p style = "text-align:left" >
- Delete Order < /p> < table style = "margin-left:20px;" >
- < tr >
- < th style = "text-align:center" >
- @Html.DisplayNameFor(model => model.OrderCode) |
- < /th> < th style = "text-align:center" >
- @Html.DisplayNameFor(model => model.OrderPrice) |
- < /th> < th > Action < /th> < /tr>
- @foreach(var item in Model) { < tr >
- < td style = "text-align:center" >
- @Html.DisplayFor(modelItem => item.OrderCode) < /td> < td style = "text-align:center" >
- @Html.DisplayFor(modelItem => item.OrderPrice) < /td> < td style = "text-align:center" >
- < input id = "Delete"
- onclick = "deleteOrder('@item.OrderID')"
- type = "button"
- value = "Delete" / >
- < /td> < /tr>
- } < /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.
- [HttpGet]
- public ActionResult Create()
- {
- return View(new OrderFood());
- }
-
- [HttpPost]
- public ActionResult Create(OrderFood OrderFood)
- {
- if (ModelState.IsValid)
- {
- TempData["Message"] = "Your Order " + OrderFood.OrderCode + "has been Saved Successfully ";
- return RedirectToAction("Create");
- } else
- {
-
- }
- return View(OrderFood);
- }
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.
- <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" rel="stylesheet" />
- <script src="~/bootstrap-3.3.6-dist/js/bootstrap.js"></script>
-
- <script src="https://lipis.github.io/bootstrap-sweetalert/lib/sweet-alert.js"></script>
- <link href="~/Content/sweetalert/sweet-alert.css" rel="stylesheet" />
-
- <script type="text/javascript">
- @if(TempData["Message"] != null) { < text >
- $(window).load(function()
- {
- $(document).ready(function()
- {
- swal({
- title: "Message",
- text: "@TempData["
- Message "]",
- type: "success"
- });
- });
- }); < /text>
- }
- </script>
Snapshot of Sweet Alert on Saving Record
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
- <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 eeference visit this
site.