Using a JQuery Modal Dialog with Checkboxes in an ASP.NET GridView

GridView with a JQuery Dialog
GridView with a JQuery Dialog

Recently I wanted to use the stock JQuery UI modal dialog confirmation widget with an ASP.NET GridView control. The image above shows the basic setup that I wanted the GridView to have.

As you can see, the grid should have several data columns followed by a column containing Checkboxes. The JQuery dialog should be triggered by the click event of each Checkbox. When the user clicks on a Checkbox in the GridView, the JQuery dialog should appear only if a Checkbox has already been selected. Furthermore, the user should be given two buttons as actions. The OK button will allow the check to happen, but the Cancel button will undo the check of the Checkbox.

The Code:

Here is the code for the fully functional example. This will run exactly as described at the beginning of this article and as shown in the top image.

<%@ Page Language="VB" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">
 Dim m_testData As New Hashtable()
 Protected Sub Page_Load(sender As Object, e As System.EventArgs)
 m_testData.Add("test_1_id", "test_1_value")
 m_testData.Add("test_2_id", "test_2_value")
 m_testData.Add("test_3_id", "test_3_value")
 m_testData.Add("test_4_id", "test_4_value")
 GridView1.DataSource = m_testData
 GridView1.DataBind()
 End Sub
</script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<style>
.ui-dialog
{
 font-size:8pt; 
 color:black; 
}
.ui-dialog-title
{
 font-size:10pt; 
 font-weight:bold;
 color:red; 
}
.ui-button
{
 font-size:10pt; 
 font-weight:bold;
 color:black; 
}
</style>
 <title></title>
</head>
<script>
 var currentId;
 $(document).ready(function () {
 loadDialog();
 $('.cbxAction').click(function (myObject) {
 currentId = myObject.target.id;
 var isOtherCbxSelected = false
 $(".cbxAction :checked").each(function () {
 var cbxIdentity = this.id;
 if (cbxIdentity != currentId) isOtherCbxSelected = true;
 })
 if (isOtherCbxSelected) {
 if (myObject.target.checked) {
 $("#btnShowModal").dialog("open");
 }
 }
 });
 });
 function loadDialog() {
 $("#btnShowModal").dialog({
 resizable: false,
 height: 140,
 width: 300,
 modal: true,
 autoOpen: false,
 buttons: {
 "OK": function () {
 $(this).dialog("close");
 },
 Cancel: function () {
 $('#' + currentId).attr('checked', false);
 $(this).dialog("close");
 }
 }
 });
 }
</script>
<body>
<form id="form1" runat="server"> 
<div id="UPDPContactPhysicalAddrList">
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
 <Columns>
 <asp:TemplateField HeaderText="key">
 <EditItemTemplate>
 <asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("key") %>'></asp:TextBox>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:Label ID="Label1" runat="server" Text='<%# Bind("key") %>'></asp:Label>
 </ItemTemplate>
 </asp:TemplateField>
 <asp:TemplateField HeaderText="value">
 <EditItemTemplate>
 <asp:TextBox ID="TextBox2" runat="server" Text='<%# Bind("value") %>'></asp:TextBox>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:Label ID="Label2" runat="server" Text='<%# Bind("value") %>'></asp:Label>
 </ItemTemplate>
 </asp:TemplateField>
 <asp:TemplateField HeaderText="checkcontrol">
 <EditItemTemplate>
 <asp:CheckBox ID="cbxEdit1" runat="server" class="cbxAction"></asp:CheckBox>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:CheckBox ID="cbxEdit2" runat="server" class="cbxAction"></asp:CheckBox>
 </ItemTemplate>
 </asp:TemplateField>
 </Columns>
</asp:GridView>
</div>
<div id="btnShowModal" title="Allow Checkbox Check?">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Are you sure that you want to check this checkbox?</p>
</div>
</form>
</body>
</html>

Breaking Down the Code:

Populating the GridView Control

From the example code above, you can see that I first populate the GridView with the contents of a hard-coded Hashtable in the Page Load event. In a real-world application, you will likely want to bind this with data from a database instead.

Referencing the JQuery Libraries

The simplest way to include the JQuery and JQuery-UI libraries into your code is by referencing them online at the JQuery.com Web site. This also means that you don’t need to include the rather sizable libraries in your project, although you should do so for a production-level project for bandwidth reasons.

Currently the latest versions of the JQuery libraries are JQuery 1.8.2 and JQuery-UI 1.9.1 and they can be referenced as follows:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.2.js"></script>
<script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>

Styling the JQuery Dialog

Next we can style the JQuery dialog for our application so that it has a font size and color scheme in line with your site design. You can find out a lot of details about the CSS structure of your dialog box by using FireBug to examine the rendered control.

<style>
.ui-dialog
{
 font-size:8pt; 
 color:black; 
}
.ui-dialog-title
{
 font-size:10pt; 
 font-weight:bold;
 color:red; 
}
.ui-button
{
 font-size:10pt; 
 font-weight:bold;
 color:black; 
}
</style>

Adding the Instance of the JQuery Dialog Box

To set the JQuery dialog up on your page you need to add a <div containing the title and body text of your dialog. The title of your dialog is read automatically from text that you enter into the title tag of your <div. Then any text that you place inside of your <div is used to populate the content of your dialog box. The buttons that you want to appear in your dialog box along with their behavior are set up in the JQuery code itself.

Here is the HTML markup for the dialog box:

<div id="btnShowModal" title="Allow Checkbox Check?">
<p><span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>Are you sure that you want to check this checkbox?</p>
</div>

The JQuery Setup

Now comes the fun part of setting up the JQuery for your new dialog box. A lot of the basic setup is available for you on the JQuery-UI examples site.

1) As usual you can set up the default look inside a function that you call when the page is ready to render using:

$(document).ready(function () {

2) In this case we will create a function called loadDialog that will set up the default look and feel of the dialog including the buttons and their behavior:

var currentId;
$(document).ready(function () {
loadDialog();
});
function loadDialog() {
$("#btnShowModal").dialog({
resizable: false,
height: 140,
width: 300,
modal: true,
autoOpen: false,
buttons: {
"OK": function () {
$(this).dialog("close");
},
Cancel: function () {
$('#' + currentId).attr('checked', false);
$(this).dialog("close");
}
}
});
}

As you can see from the code above, the loadDialog function sets several options for the dialog widget’s appearance and then sets up the behavior of each of the two buttons.

It’s worth noting that you will want to set the autoOpen option to false so that the dialog is invisible until the user clicks on a Checkbox control in your GridView. I have highlighted this option in green in the code above.

Setting up the Custom JQuery Dialog Widget Behavior

The final requirement after we have hooked up the JQuery dialog widget to our CheckBox controls is to add the business logic that the widget should only appear when a CheckBox is clicked but another CheckBox has already been checked:

$('.cbxAction').click(function (myObject) {
 currentId = myObject.target.id;
 var isOtherCbxSelected = false
 $(".cbxAction :checked").each(function () {
 var cbxIdentity = this.id;
 if (cbxIdentity != currentId) isOtherCbxSelected = true;
 })
 if (isOtherCbxSelected) {
 if (myObject.target.checked) {
 $("#btnShowModal").dialog("open");
 }
 }
 });

This custom code begins by hooking up each CheckBox in the GridView control with a JQuery Dialog click event. However rather than adding the code to each object in the GridView, as used to be the case, we can simply tell JQuery to do so using a shared CssClass between each CheckBox control. Specifically, we have given each CheckBox the custom class cbxAction and we tell JQuery to associate a click event with each by using the syntax:

$('.cbxAction').click(function (myObject) {

Also, note that in the custom function called by the click event, that we are accepting a variable called myObject, which JQuery passes in as the HTML object to which the event took place.

Within the custom click function, we immediately get the Id of the clicked CheckBox using:

currentId = myObject.target.id;

After we have the Id of the clicked object, we want to check if any CheckBoxes exist in the GridView, other than the currently clicked CheckBox, that have previously been checked. We do so in a loop using the .each method, and use JQuery’s inbuilt filtering for checked CheckBoxes as:

$(".cbxAction :checked").each(function () {

We can get the Id of each of the CheckBox controls inside of the loop using this.id;

Finally we can tell JQuery to open the modal dialog box using the command:

$("#btnShowModal").dialog("open");

Summary

The JQuery modal dialog widget is a nicely designed component, and the syntax for working with it is pleasantly terse and concise while still remaining flexible for customization. This is certainly a component that I will continue to use with my applications.

Further Resources:

The API for the JQuery Dialog Widget

Advertisements

3 thoughts on “Using a JQuery Modal Dialog with Checkboxes in an ASP.NET GridView

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s