ASP.NET MVC Display Confirm Dialog Before Submitting A Form Using jQuery UI Dialog
Good evening.
Cheers!
Here's an ASP.NET MVC example of showing a confirm dialog with yes/no button that returns a result either to submit a form or not using jQuery UI Dialog. This is useful especially if the form consists of multiple buttons that have the capability to submit a form. Say for example, a form has a save and delete buttons inside the BeginForm() statement and you want to extend the feature of the delete button that is to notify the user if he/she wishes to proceed with removing the form information. The existing method of showing a confirm dialog which has been practiced since ASP Classic is using the JavaScript Window.confirm dialog. But for this demo, I'll choose the jQuery UI Dialog instead of the traditional confirm dialog because the UI is more presentable to the user and this tutorial won't include database interaction for simplicity sake.
To begin with, create an empty ASP.NET MVC project and add Nuget packages for jQueryUI.Combined and Bootstrap. Then add a class called Contact inside the Models folder.
public class Contact { [Display(Name = "Contact Name")] public string ContactName { get; set; } [Display(Name = "Address")] public string ContactAddress { get; set; } [Display(Name = "Attention")] public string ContactAttention { get; set; } [Display(Name = "Phone")] public string ContactPhone { get; set; } [Display(Name = "Professional Fee")] public double ContactProfessionalFee { get; set; } public string Activity { get; set; } public int ContactID { get; set; } public Contact() { ContactID = 0; ContactName = string.Empty; ContactAddress = string.Empty; ContactAttention = string.Empty; ContactPhone = string.Empty; ContactProfessionalFee = 0; Activity = string.Empty; } }
Next is to insert a controller class inside the Controllers folder called Home with two ActionResult() methods. As I've mentioned above, we don't deal with the database and focus mainly on showing the confirm dialog.
The ManageContacts() method with HttpPost attribute has a condition that will check if a delete button was chosen. Otherwise, the save button is selected. No fancy codes were added for this demo but in your case, you might want to add some database interaction if you wish to.
public class HomeController : Controller { public ActionResult ManageContacts() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult ManageContacts(Contact contactModel) { try { if (!string.IsNullOrEmpty(contactModel.Activity)) { if (contactModel.Activity.Equals("Delete", StringComparison.OrdinalIgnoreCase)) { //Delete codes here.... return RedirectToAction("Index"); } } //save codes here.... } catch (Exception ex) { return View(); } return RedirectToAction("Index"); } }
Then add a ManageContacts view with the model bound to each individual controls for entry purposes and the ContactID as hidden field. The most significant code lies inside the script tag. In there, I added a click method for the delete button that will disable the default behavior to submit the form. This executes the DeleteContact() function that calls the ConfirmDelete() function that returns the value of a button which is selected on the dialog box. The values are returned using the jQuery Deferred method. Based from the jQuery API, this factory function returns a chainable utility object with methods to register multiple callbacks into callback queues, invoke callback queues, and relay the success or failure state of any synchronous or asynchronous function. This is useful since our dialog is based on asynchronous model.
@model DialogConfirmDemo.Models.Contact @{ ViewBag.Title = "Manage Contacts"; } @using (Html.BeginForm("ManageContacts", "Home", FormMethod.Post, new { id = "frmContact", enctype = "multipart/form-data" })) { @Html.AntiForgeryToken() @Html.HiddenFor(m => m.Activity) @Html.HiddenFor(m => m.ContactID) <div class="form-horizontal"> <h4>Manage Contacts</h4> <hr /> <div class="form-group"> @Html.LabelFor(model => model.ContactName, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ContactName, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ContactName, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ContactAddress, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ContactAddress, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ContactAddress, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ContactAttention, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ContactAttention, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ContactAttention, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ContactPhone, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ContactPhone, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ContactPhone, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> @Html.LabelFor(model => model.ContactProfessionalFee, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-10"> @Html.EditorFor(model => model.ContactProfessionalFee, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.ContactProfessionalFee, "", new { @class = "text-danger" }) </div> </div> <div class="form-group"> <div class="col-md-offset-2 col-md-10"> <button id="cmdSave" type="submit" name="submit" value="Send" class="btn btn-default"> <span class="glyphicon glyphicon-send"></span> Submit </button> <button id="cmdDelete" type="submit" name="submit" value="Delete" class="btn btn-default"> <span class="glyphicon glyphicon-remove"></span> Delete </button> </div> </div> </div> } <link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" /> <script src="~/Scripts/jquery-ui-1.12.1.js"></script> <script type="text/javascript"> var postUrl = '@Url.Action("ManageContacts", "Home")'; $(function () { $('#cmdDelete').click(function (e) { e.preventDefault(); DeleteContact(); }); }); function DeleteContact() { var question = "Do you want to delete this contact info?"; ConfirmDelete(question).then(function (answer) { var ans = (String(answer) === "true"); if (ans) { $('#Activity').val('Delete'); var data = $('#frmContact').serialize(); $.ajax({ type: "POST", url: postUrl, data: data }); } }); } function ConfirmDelete(question) { var defer = $.Deferred(); $('<div id="id="divDeleteClientRequest""></div>') .html(question) .dialog({ autoOpen: true, modal: true, draggable: true, title: 'Confirm Delete', buttons: { "Yes": function () { defer.resolve("true"); $(this).dialog("close"); }, "No": function () { defer.resolve("false"); $(this).dialog("close"); } }, close: function () { $(this).dialog('destroy').remove(); } }); return defer.promise(); } </script>
If you run the application and click the submit button, it will directly POST the form to the controller.However for the delete button when clicked, it will show a jQuery UI Dialog prompting the user to proceed deleting or not as depicted on the sample screenshots below.
Cheers!
Comments
Post a Comment