Disable an ASP.NET Button During PostBack with AJAX Loading Background Image

No.of Views1976
Bookmarked0 times
Downloads 
Votes0
By  bryiantan   On  16 Feb 2010 01:02:15
Tag : ASP.NET , ASP.NET Controls
Disable an ASP.NET Button During PostBack with AJAX Loading Background Image
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

There are times when our applications might take an extra few seconds to respond to a click event. Some users might get impatient and click on the button more than once. We can easily avoid this type of situation by disabling the submit button during PostBack on the page by using a client side script. In this article, I will share with everyone on how to:

  1. Disable the button during PostBack with or without the present of validation control
  2. Change the button text value during PostBack
  3. Include an AJAX loading background image during PostBack
  4. How I avoided the 'Page_IsValid is undefined' JavaScript error

Using the Code

Before we begin, allow me to show you the structure of my project. You are welcome to download this demo.

Image Loading

Demo 1 – Without Validation Control

Here is the content of the Jscript.js

function disableBtn(btnID, newText) {var btn = document.getElementById(btnID);
        setTimeout("setImage('"+btnID+"')", 10);
        btn.disabled = true;
        btn.value = newText;
}

function setImage(btnID) {var btn = document.getElementById(btnID);
    btn.style.background = 'url(12501270608.gif)';
}

Here is part of the Default.aspx page content.

<table><tr><td>td><td>
<asp:button id="btnOne" tabIndex="0" Runat="server" Text="Submit"                     onclick="btnOne_Click"                     OnClientClick="disableBtn(this.id, 'Submitting...')"                     UseSubmitBehavior="false" />
td>tr><tr><td colspan="2"><asp:Label ID="Label3" runat="server" Text="">asp:Label>td>tr>table>
<script type="text/javascript" src="JScript2.js">script>

In Default.aspx page, I have a button and a label control. Let take a closer look at the button attributes.

OnClientClick="disableBtn(this.id, 'Submitting...')" - Calls the JavaScript function by passing in the button ID and the new text value that I want it to display on click. UseSubmitBehavior="false" - Indicates that the button control should use the ASP.NET postback mechanism instead of client browser's submit mechanism ( UseSubmitBehavior Property )

For testing, I included these lines in the default.aspx.cs

protected void btnOne_Click(object sender, EventArgs e)
{
    Thread.Sleep(2000);
    Label3.Text = sb.ToString();
}

Here how's the button will look like when someone click on it.

Image Loading
Image Loading

Demo 2 – With Validation Control

Here is the output from Default2.aspx

Image Loading

Ops... The button is still disabled after it failed the validation process. Let modify the JavaScript to fix this problem.

Image Loading

Here is the content of the new JavaScript with comments– Jscript2.js

function ResetToDefault(btn, oldValue) {
btn.disabled = false;
btn.value = oldValue;
}
//browser propertiesvar Browser = {
Version: function() {
var version = 999;
if (navigator.appVersion.indexOf("MSIE") != -1) {
version = parseFloat(navigator.appVersion.split("MSIE")[1]); return version;
}
},
Name: navigator.appName,
isIE: function() {
if (navigator.appVersion.indexOf("MSIE") != -1) {
return true;
}
return false;
}
};

//Handle Page_Validators is not defined error//http://www.velocityreviews.com/forums/t88987-pagevalidators-error.htmlfunction HasPageValidators() {
var hasValidators = false;
try {
if (Page_Validators.length > 0) {
hasValidators = true;
}
}
catch (error) { }

return hasValidators;
}


function SetImage(btn) {

if (btn.type == "image") {
btn.src = null;
btn.style.width = '100px';
btn.style.height = '20px';
btn.style.backgroundImage = 'url(http://images.ysatech.com/ajax-loader.gif)';
}
else {
//somehow backgroundImage not working with IE 7if (Browser.isIE() && Browser.Version() === 7) {
btn.style.background = 'url(http://images.ysatech.com/ajax-loader.gif)';
}
else {
btn.style.backgroundImage = 'url(http://images.ysatech.com/ajax-loader.gif)';
}
}
}

//enable the button and restore the original text value for browsers other than IEfunction EnableOnUnload(btn, btnText) {
if (!Browser.isIE()) {
window.onunload = function() {
ResetToDefault(btn, btnText);
};
}
}

//check if the validator have any control to validatefunction EnableValidator(validator) {
var controlToValidate = document.getElementById(validator.controltovalidate);

if (controlToValidate !== null) {
// alert(controlToValidate.id);ValidatorEnable(validator);
return true;
}
ValidatorEnable(validator, false);

return false;
}

function disableBtn(btnID, newText) {
var btn = document.getElementById(btnID);
var oldValue = btn.value;
btn.disabled = true;
btn.value = newText;

//if validator control presentif (HasPageValidators()) {

Page_IsValid = null;

//http://sandblogaspnet.blogspot.com/2009/04/calling-validator-controls-from.html//double check, if validator not nullif (Page_Validators !== 'undefined' && Page_Validators !== null) {
//Looping through the whole validation collection.for (var i = 0; i < Page_Validators.length; i++) {

var validator = Page_Validators[i];

//check if control to validate is enable if (EnableValidator(validator)) {

if (!Page_Validators[i].isvalid) { //if not validResetToDefault(btn, oldValue); //break;}
}
}

// else { //if validvar isValidationOk = Page_IsValid;

alert('isValidationOk ' + isValidationOk);

EnableOnUnload(btn, btn.value);
if (isValidationOk !== null) {
if (isValidationOk) {
SetImage(btn);
__doPostBack(btnID, '');
// break;}
else { //page not validbtn.disabled = false;
}
}
// }}
}
else { //regular, no validation control present// setTimeout("SetImage('" + btn + "')", 5);SetImage(btn);
btn.disabled = true; btn.value = newText;
EnableOnUnload(btn, btn.value);
}
}

//disable those validators where controltovalidate = nullfunction DisableValidators() {
//this will get rid of the Page_Validators is undefined errorif (typeof (Page_Validators) === 'undefined')
return;

if (Page_Validators !== 'undefined' && Page_Validators !== null) {
for (var i = 0; i < Page_Validators.length; i++) {
var validator2 = Page_Validators[i];
var controlToValidate2 = document.getElementById(validator2.controltovalidate);
if (controlToValidate2 === null) {
ValidatorEnable(validator2, false);
}
}
}
return false;
}

window.onload = DisableValidators;

Output from using the new JavaScript (JScript2.js)

Image Loading

 

Image Loading

 

Image Loading

Conclusion

The main items in this project were the JavaScript (Jscript2) and the button attributes (OnClientClick, UseSubmitBehavior)

I hope someone will find this tutorial useful. If you think I still can improve this code, please leave me a feedback and share your thought.

Tested on IE 6.0/7.0 and Firefox 3.0.13

Demostration

View this project in action

Sample Project Source 

Download source files -22 kb

 
Sign Up to vote for this article
 
About Author
 
bryiantan
Occupation-
Company-
Member Type-Fresh
Location-Not Provided
Joined date-30 Jul 2009
Home Page-
Blog Page-
 
 
Other popularSectionarticles
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top