The ASP.NET Ajax Control Toolkit includes an “Confirm Button” control extender.
In this series I’ve been demonstrating ways to implement the features of the MS Ajax Toolkit with jQuery and in this post I’ll address the “Confirm Button Extender”.
You might think that doing this is so trivial that it wouldn’t warrant a blog post but there is more to it that you might guess at first glance.
In ASP.NET WebForms there is a definite abstraction of the underlying web application mechanics and, for the purposes of this subject there some issues we must consider.
  1. By default, ASP.NET WebForms is a SERVER side programming model and therefore all UI elements (ASP.NET Controls) with user interactions are assumed to have server-side logic.
  2. We are integrating Client AND Server Development Models.
  3. An ASPX (Web Forms) page is assumed to contain only ONE HTML form. (Though we can use advanced manual techniques to bypass this limitation)
  4. Given the above items 1 & 3, all <asp:button> controls render as HTML Submit elements.
So what does that mean ?
HTML actually has three button types :
  • <INPUT TYPE=BUTTON> // A button with a click event.
  • <INPUT TYPE=SUBMIT> // A button whose click posts the html form
  • <INPUT TYPE=RESET> // A button that causes form fields to be reset
So, ASP.NET Buttons all render to HTML SUBMIT buttons.
We can divide button triggered dialogs into two groups:
  • Ones that display something but have no need to SUBMIT The form
  • Ones that take user input and MIGHT submit the form.
Perhaps the most straight forward way to implement both of these categories of button click dialogs is to use input type=”button” for all our buttons and programmatically submit the form when appropriate.
I’ve created a collection on customized buttons with OnClick dialogs:
Each of these will implement different usages of the jQuery.Alert plugin you can find [ HERE ]
The first button is wired to an information only dialog that will display for (in our case) 3 seconds.
Lets look at the markup, the CSS and the page specific JavaScript and then we’ll enumerate the rest of the button behaviors.
The Markup looks like this :

<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
<link href='Styles/jqdialog.css' rel='stylesheet' type='text/css' />
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
<br />
<button ID='btnotify' type='button' class='CustomButton'>
        Notification Popup
</button><br /><br />
<button ID='btalert' type='button' class='CustomButton'>
        Alert Popup
</button><br /><br />
<button ID='btconfirm' type='button' class='CustomButton'>
        Confim Dialog
</button><br /><br />
<button ID='btprompt' type='button' class='CustomButton'>
        Input Prompt
</button><br /><br />
<button id='btcontent' type='button' class='CustomButton'>
        Any Custom Content
</button><br /><br />

<script src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js'
        type='text/javascript'></script>
<script src='Scripts/jqdialog.min.js' type='text/javascript'></script>
<script src='Scripts/jQueryDialogs.js' type='text/javascript'></script>
</asp:Content>

Note that the concise markup does not reflect the rich functionality associated with the buttons.
The CSS class designation [class="CustomButton"] is responsible for the styled appearance of the buttons but not the behavior. Often when using jQuery we will use a data attribute or a class identifier to connect the desired jQuery code to the HTML elements but since button dialogs are likely to be very specific (one dialog for each button), the jQuery behaviors in this demo will be connection via the button element ID.
The CSS is as follows. Note that the Custom Button class is at the bottom and all the rest of the CSS defines the visuals for the various dialogs. In your app you would only include the classes that you use on your pages.

#jqDialog_box
{
    position: absolute;
	width: 450px;
	height: 150px;
    border-bottom: #ccc 3px solid;
	border-left: #ccc 1px solid;
	border-top: #ccc 1px solid;
	border-right: #ccc 3px solid;
	font-family: Arial;
	background: #f5f5f5;
}

#jqDialog_content {
	margin: 10px;
	height: 90px;
	font-size: 12px;
	overflow: hidden;
	font-weight: bold;
}

#jqDialog_options {
	text-align: center;
	margin: 10px;
}

#jqDialog_options BUTTON {
	border-bottom: 0px;
	border-left: 0px;
	border-right: 0px;
	border-top: 0px;
	margin-right: 5px;
	width: auto;
	font-family: Arial;
	background: #000;
	color: #fff;
	font-size: 1.5em;
	cursor: pointer;
}

#jqDialog_input {
	padding-bottom: 4px;
	padding-left: 4px;
	padding-right: 4px;
	padding-top: 4px;
	width: 250px;
}

#jqDialog_close {
	border-bottom: medium none;
	border-left: medium none;
	BORDER-TOP: medium none;
	border-RIGHT: medium none;
	background: none transparent scroll repeat 0% 0%;
	float: right;
	color: #ff0000;
	font-size: 10px;
	font-weight: bold;
	cursor: pointer;
}

.CustomButton {
    background-color: #99CCFF;
    border: thin solid #008080;
    width: 200px;
    cursor: pointer;
}

And our page specific JavaScript is :

// Notification dialog
$('#btnotify').click(function () {
    $.jqDialog.notify('<br /><br /><br />' +
                      '<center><strong>This dialog will disappear in ' +
                      '3 seconds</center>',
                       3);
});

// Alert dialog
$('#btalert').click(function () {
    $.jqDialog.alert('<br /><br /><center>
	                 <strong>This alert requires user ' +
                     'interaction.</strong></center>', function () {
                     // callback function for 'OK' button
                     alert('User Clicked OK');
    });
});

// Confirm dialog
$('#btconfirm').click(function () {
    $.jqDialog.confirm('<br /><br /><center><strong>Are you sure ??? ' +
                       ' </strong></center>',
                       // callback function for 'YES' button
                       function () {
                                   document.forms[0].submit();
                                   },
                       // callback function for 'NO' button
                      function () {
                                  // No Op
                                  }
                      );
});

// prompt
$('#btprompt').click(function () {
    $.jqDialog.prompt('<br /><br />Please enter your name to agree',
		  '',
		  // callback function for 'OK' button
		  function (data) {
						  if (data == '') {
							  return;
						  }
						 else {
							  alert('Your name ' + data + ' is approved.');
							  document.forms[0].submit();
							  }
						 },
						// callback function for 'Cancel' button
		  function () {
					  // No Op
					  }
		  );
});

// custom cotent dialog
$('#btcontent').click(function () {
    $.jqDialog.content('No dialog controls, but any markup you want.
	                    <br /><br />' +
					   '<input type='text' name='test' /><br /><br />' +
					   'Click the 'X' in the upper right corner to close.');
});

The JavaScript code that is specific to the first Button Popup is this:


// Notification dialog
$('#btnotify').click(function () {
    $.jqDialog.notify('<br /><br /><br />' +
                      '<center><strong>This dialog will disappear in ' +
                      '3 seconds</center>',
                       3);
});

Note the last parameter to the notify function is a number 3 (for 3 seconds), change the amount of time the dialog is visible by changing that parameter.

The second example is also an informational dialog but instead of automatically closing after three seconds, this one requires the user to close it manually.
This Dialog calls the ALERT function in the jQuery plugin :

// Alert dialog
$('#btalert').click(function () {
    $.jqDialog.alert('<br /><br /><center>
	                  <strong>This alert requires user ' +
                     'interaction.</strong></center>', function () {
                     // callback function for 'OK' button
                     alert('User Clicked OK');
    });
});

Note that the alert method of this jQuery plugin takes a callback function so that when the user clicks the button in the dialog we can execute some JavaScript code.

In our case – we’ll just pop up a JavaScript Alert for testing purposes but you can run any JavaScript you like.
In the third iteration we’ll add a bit of complexity.
Now we have user input with multiple choices. The common scenario for this is the stereotypical “Confirm Submit” where the user gets one last chance to decide whether or not to post the form back to the server.
To do this we’ll use the jQuery Plugin’s confirm() method. This will take care of the “kind” of dialog that we want but you will recall that I mentioned previously we were using input buttons of type=button rather than submit. Since we’re doing this we’ll need to post the form (submit) by calling our HTML form’s submit method manually.

// Confirm dialog
$('#btconfirm').click(function () {
    $.jqDialog.confirm('<br /><br /><center><strong>Are you sure ??? ' +
                                ' </strong></center>',
                               // callback function for 'YES' button
                               function () {
                                           document.forms[0].submit();
                                           },
                               // callback function for 'NO' button
                               function () {
                                           // No Op
                                           }
     );
});

The confrm() method takes 3 parameters:

  • The text to display in the dialog
  • A function reference to be called if the user responds in the affirmative
  • A function reference to be called if the user responds in the negative
You can see in line #7 above [ document.forms[0].submit(); ] we submit the form. Since ASP.NET Web Forms pages have only one form and it is not named (assuming you are using the default site template) we can always resolve it’s methods via the first item in the forms collection [0]
Since we are posting the form from JavaScript and not an ASP.NET button control there is a minor difference in ou post back event handling.
Since the Button is not a server control (no runat=server) we will not have a server side button click event handler.
No problem:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
        // Do whatever you need jere.
        }
    }

}

Instead of a server side button click event handler we simply add a test for “IsPostBack” to our page’s Page_Load event handler and implement any button specific server side logic there.

If we wanted to add user input (text) to the confirm dialog we can use the Query Plugin’s prompt() method.
A common scenario for this is to ask the user to provide their name as a type of signature to indicate acceptance for something defined in the dialog’s text.
The JavaScript code is as follows:

// prompt
$('#btprompt').click(function () {
    $.jqDialog.prompt('<br /><br />Please enter your name to agree',
		  '',
		  // callback function for 'OK' button
		  function (data) {
						  if (data == '') {
							  return;
						  }
						 else {
							  alert('Your name ' + data + ' is approved.');
							  document.forms[0].submit();
							  }
						 },
						// callback function for 'Cancel' button
		  function () {
					  // No Op
					  }
		  );
});

The “data” argument contains the user input and we can do with it as we please.

Of course, you can probably envision more complex dialog scenarios and the jQer.Alert plugin includes a content() method that lets us pass pretty much any HTML markup that we like to be displayed in the dialog.
The page specific JavaScript is :

// custom cotent dialog
$('#btcontent').click(function () {
    $.jqDialog.content('No dialog controls, 
	                    but any markup you want.<br /><br />' +
					   '<input type='text' name='test' /><br /><br />' +
					   'Click the 'X' in the upper right corner to close.');
});

Hopefuly these options give you all you need to implement the kinds of Confirm Button Dialogs you will need in your applications.

You can download the source code [ HERE ].