AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=1894&pId=-1
Disable an ASP.NET Button Control During Postback with an AJAX Loading Background Image
page
by Bryian Tan
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 52773/ 132

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 a button during PostBack with or without the present of a validation control.

2.    Change button text value during PostBack.

3.    Include an AJAX loading background image during PostBack.

4.    How to avoid the 'Page_IsValid is undefined' or ' Page_Validators is not defined' 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.

Figure 1

 

Demo 1 – Without Validation Control

Here is the content of Jscript.js:

Listing 1

function disableBtn(btnID, newText) {
 
    var btn = document.getElementById(btnID);
        setTimeout("setImage('"+btnID+"')", 10);
        btn.disabled = true;
        btn.value = newText;
}
//using absolute url for image to avoid complication
function setImage(btnID) {
    var btn = document.getElementById(btnID);
    btn.style.background = 'url(http://images.ysatech.com/ajax-loader.gif)';
}

Here is part of the Default.aspx page content:

Listing 2

<table>        
         <tr>
            <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=""></td>
        </tr>
   </table>
 
<script type="text/javascript" src="JScript.js"></script>

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

Listing 3

<span lang=CS>protectd void btnOne_Click(object sender, EventArgs e)</span>
<span lang=CS>{</span>
<span lang=CS>    Thread.Sleep(2000);</span>
<span lang=CS>    Label3.Text = DateTime.Now.ToLongTimeString();</span>
<span lang=CS>}</span>

In the Default.aspx page, I have a Button and a Label control. Let's 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 event. The JavaScript will gray out the button, set new text ('processing…') and display Ajax loading background image.

·         UseSubmitBehavior="false" - Indicates that the button control should use the ASP.NET postback mechanism instead of the client browser's submit mechanism (UseSubmitBehavior property).

Here is how the button will look like when someone clicks on it:

Figure 2

 

Figure 3

Demo 2 – With Validation Control

Here is the output from Default2.aspx:

Figure 4

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

Figure 5

Here is the content of the new JavaScript file with comments – JScript2.js:

Listing 4

function disableBtn(btnID, newText) {
    var btn = document.getElementById(btnID);
    var oldValue = btn.value;
    btn.disabled = true;
    btn.value = newText;
    if (HasPageValidators()) {
        if (Page_Validators != undefined && Page_Validators != null) {
            //Looping through the whole validation collection.
            for (var i = 0; i < Page_Validators.length; i++) {
                ValidatorEnable(Page_Validators[i]);
                //if condition to check whether the validation was successfull or not.
                if (!Page_Validators[i].isvalid) {ResetToDefault(btn, oldValue); break;   }
                else {
                    var isValidationOk = Page_IsValid; EnableOnUnload(btn, btn.value);
 
                    if (isValidationOk !== null) {
                        //page valid
                        if (isValidationOk) {
                            SetImage(btn);
                            break;
                        }
                        else { //page not valid
                            btn.disabled = false;
                        }
                    }
                }
            }
        }
    }
    else {
        SetImage(btn);
        btn.disabled = true; btn.value = newText;
        EnableOnUnload(btn, btn.value);
    }
}
function ResetToDefault(btn, oldValue) {
    btn.disabled = false;
    btn.value = oldValue;
}
 
//Handle Page_Validators is not defined error
function HasPageValidators() {
    var hasValidators = false;
    try {
        if (Page_Validators.length > 0) {
            hasValidators = true;
        }
    }
    catch (error){}
    return hasValidators;
}
 
function SetImage(btn) {
    btn.style.background = 'url(http://images.ysatech.com/ajax-loader.gif)';
}
 
//enable the button and restore the original text value for browsers other than IE
function EnableOnUnload(btn, btnText) {
    if (navigator.appName !== 'Microsoft Internet Explorer') {
        window.onunload = function() {
            ResetToDefault(btn, btnText);
        }
    }
}

In the JavaScript function disableBtn, first I check if the page contains any validation controls else set the background image, text, disable the button and call the function EnableOnUnload. I found out that, in Firefox, if we hit the button and continue to the next page, and then hit the Back button (or javascript:history(-1);)... the button control is still disabled. The purpose of the function EnableOnUnload is to enable the button and restore the original text value during the onunload event for browsers other than IE. If the page have validation controls and fail the validation process, do not disable the button else set the background image, text, disable the button and call the function EnableOnUnload.

Output from using the new JavaScript (JScript2.js), when fail validation process:

Figure 6

Figure 7

Figure 8

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 can improve this code, please leave me a feedback and share your thoughts.

Tested on IE 6.0/7.0 and Firefox 3.0.13.

 

History

·         08/14/2009 - I found out that, in Firefox, if we hit the button and continue to the next page, and then hit the Back button (or javascript:history(-1);)... the button control is still disabled. I have updated the JavaScript (JScript2). I have not fully tested the new implementation. Please leave me a feedback and share your thoughts.

·         10/19/2009 - Modified the JavaScript(JScript2) to fix the double validation problem.

 

References

Button..::.UseSubmitBehavior Property

Calling validator controls from Javascript

ASP Net - Page_Validators error

 

Demo
Downloads


©Copyright 1998-2018 ASPAlliance.com  |  Page Processed at 2018-12-11 9:26:58 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search