See It In Action

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:
<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:
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:
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:
@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;">
</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:
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.
<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:
$(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.
|