Creating A jQuery Modal Confirmation Dialog When Submitting a Form

modified

Introduction

Accepting input from users through the use of HTML forms is a common task in almost any web application. When a web application form is lengthy or detailed in nature, it may be a good idea to display a confirmation of the values the user entered, prior to submitting the data. Rather than navigating the user away from the form to display the confirmation, web applications can take advantage of javascript (particularly jQuery and jQuery UI) to display a modal popup dialog containing the form field values. The user can confirm the fields and choose to make changes or submit the data.

In this tutorial, we’ll walk through the steps of creating an easy confirmation modal dialog with C# ASP .NET MVC3, jQuery, and jQuery UI. Our confirmation dialog will display all form fields that contain values (leaving any fields without values hidden). It will allow the user to click Edit to close the dialog and make changes, or click Submit to submit the data to our web application for processing. Upon clicking Submit, the modal dialog’s button will automatically disable to prevent duplicate submissions. Our form confirmation dialog will also automatically grab the values from textboxes, dropdown select lists, and checkbox fields to display the confirmation data.

See It In Action

C# MVC jQuery Modal Confirmation Dialog Form Submit

Setting Up the Includes

Before getting started, we’ll need to add a few javascript and CSS files to our projects. We can take advantage of the jQuery CDN (content distribution network) hosted links to use the libraries in our C# MVC web application. In our example, we’ve modified the _Layout.cshtml file to include the following lines:

1
2
3
4
5
6
<link href="@Url.Content("~/Content/jQueryUI/jquery-ui-1.8.18.custom.css")" rel="stylesheet" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/mvc/3.0/jquery.validate.unobtrusive.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/script.js")" type="text/javascript"></script>

The above simply includes references to the jQuery and jQuery UI libraries, as well as their associated CSS code. This is required for our form validation and modal confirmation dialog.

A Simple Model

We’ll use the following simple C# MVC model for our example form:

1
2
3
4
5
6
7
8
9
10
11
12
public class Contact
{
[Required]
public string Name { get; set; }

[Required]
[RegularExpression(@"^\S+@\S+\.\S+$",
ErrorMessage = "Please enter a valid email address.")]
public string Email { get; set; }

public int Color_ID { get; set; }
}

Our Contact class will let the user enter their Name, Email, and favorite Color. We’ve included some simple data annotations to validate the three fields. Note, Color_ID will actually be a drop-down list, populated from our helper method ColorManager.GetColorList(). This method is defined as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public static class ColorManager
{
public static List<SelectListItem> GetColorList()
{
List<SelectListItem> resultList = new List<SelectListItem>();

resultList.Add(new SelectListItem { Text = "Red", Value = "1" });
resultList.Add(new SelectListItem { Text = "Green", Value = "2" });
resultList.Add(new SelectListItem { Text = "Blue", Value = "3" });

resultList.Insert(0, new SelectListItem { Text = "Please choose ..", Value = "0" });

return resultList;
}
}

The above is a simple helper method to return a list of drop-down elements to populate our HTML select element. You would most likely load this list from your database in a production C# ASP .NET MVC web application.

With our model defined, we can now begin the HTML form.

Our Easy HTML Form

Our HTML contact form can be defined in our MVC web application, using Razor code, as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
@using (Html.BeginForm("Index", "Home", FormMethod.Post, new { id = "contactForm", name = "contactForm" }))
{
@Html.ValidationSummary()

<h1>Contact Information</h1>

<div id="contactInformation" style="padding: 0 0 0 15px;">
<div>
<div style="float: left; width: 110px;">
@Html.LabelFor(e => e.Name, "Name")
</div>
<div style="float: left;">
@Html.TextBoxFor(e => e.Name)
@Html.ValidationMessageFor(e => e.Name)
</div>
</div>
<div style="clear: both;"></div>
<div>
<div style="float: left; width: 110px;">
@Html.LabelFor(e => e.Email, "Email")
</div>
<div style="float: left;">
@Html.TextBoxFor(e => e.Email)
@Html.ValidationMessageFor(e => e.Email)
</div>
</div>
<div style="clear: both;"></div>
<div>
<div style="float: left; width: 110px;">
@Html.LabelFor(e => e.Color_ID, "Favorite Color")
</div>
<div style="float: left;">
@Html.DropDownListFor(e => e.Color_ID, ColorManager.GetColorList())
@Html.ValidationMessageFor(e => e.Color_ID)
</div>
</div>
<div style="clear: both;"></div>
</div>

<div id="submitControls" style="padding: 25px 0 0 15px;">
<div>
<div style="float: left; width: 110px;">
&nbsp;
</div>
<div style="float: left;">
<input type="submit" title="Register" value="Register" id="btnRegister" />
</div>
</div>
<div style="clear: both;"></div>
</div>
}

Note, we’ve included validation elements for each model field. The Name and Email fields are required fields, while the Color is an option field. This will allow us to test the jQuery modal confirmation dialog to see the different values populated.

Our Form Controller

Once we create our MVC controller, we can successfully submit the form data for processing. We’ll then add our confirmation dialog. The code for the controller is shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new Contact());
}

[HttpPost]
public ActionResult Index(Contact contact)
{
if (ModelState.IsValid)
{
return View();
}
else
{
return View();
}
}
}

Our controller has two action methods. The first one is for rendering the initial form with a blank Contact object (upon an HTTP GET request). The second action is for submitting the form. Fairly simple.

A Form Submit Modal Confirmation Dialog

For our jQuery form confirmation dialog, we’ll need to add a small block of HTML to our page to draw the dialog.

1
2
3
4
5
6
7
8
9
10
11
12
<div id="confirmDialog" title="Confirm Details">
<p>Please confirm your details.</p>
<div>
Name: <span id="confirmName" />
</div>
<div>
Email: <span id="confirmEmail" />
</div>
<div>
Favorite Color: <span id="confirmColor" />
</div>
</div>

It’s as simple as that. We create a div for our jQuery UI modal dialog and include a set of child div elements - one for each form field. If a form field has no value, we’ll hide the element div. Otherwise, the user will see the fields and can make changes or submit the form.

Next, we need a little Javascript to power our confirmation dialog.

Populating the Confirmation Dialog with Data

When our modal form confirmation dialog displays, we can populate the fields to allow the user to confirm the form data, using the following javascript hook on the form.submit() event. This idea orginates from Jensbits modal dialog post:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
$(document).ready(function () {
// Confirmation Dialog
$('#confirmDialog').dialog({
autoOpen: false,
width: 500,
modal: true,
resizable: false,
buttons: {
"Submit": function () {
$(".ui-dialog-buttonpane button:contains('Submit')").button("disable");
$(".ui-dialog-buttonpane button:contains('Edit')").button("disable");
document.contactForm.submit();
},
"Edit": function () {
$(this).dialog("close");
}
}
});

$('#contactForm').submit(function (e) {
e.preventDefault();

// Validate the fields with MVC validation.
if ($(this).valid()) {
var field;
var confirmDiv;

// Textbox.
field = $("#Name");
confirmDiv = $("#confirmName");
if (field.val() == '') {
confirmDiv.parent().hide();
}
else {
confirmDiv.parent().show();
confirmDiv.html(field.val());
}

// Textbox.
field = $("#Email");
confirmDiv = $("#confirmEmail");
if (field.val() == '') {
confirmDiv.parent().hide();
}
else {
confirmDiv.parent().show();
confirmDiv.html(field.val());
}

// Dropdown list.
field = $("#Color_ID");
confirmDiv = $("#confirmColor");
if (field.val() == '0') {
confirmDiv.parent().hide();
}
else {
confirmDiv.parent().show();
confirmDiv.html($("#Color_ID option:selected").text());
}

$('#confirmDialog').dialog('open');
}
});
});

The above jQuery code hooks onto the form.submit() event to display the modal confirmation dialog. It goes through each form field and populates the value for the form field element. If the value is empty, we hide the parent container div. This allows our confirmation dialog to only display fields with values entered, offering easy viewing for users confirming their data. Upon clicking the Submit button in the confirmation dialog, we call the underlying form’s submit method, which bypasses the jQuery call, and submits the form data to our C# MVC web application for processing.

Download @ GitHub

You can download the project source code on GitHub by visiting the project home page.

About the Author

This article was written by Kory Becker, software developer and architect, skilled in a range of technologies, including web application development, machine learning, artificial intelligence, and data science.

Share