Disable an ASP.NET Button Control During Postback with an AJAX Loading Background Image
page 2 of 7
by Bryian Tan
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 43103/ 59

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


View Entire Article

User Comments

Title: nor   
Name: L;JL;KJ
Date: 2012-08-29 12:14:11 AM
Comment:
LKJ;LJ
Title: gdfg   
Name: dgdfgd
Date: 2012-04-29 4:19:49 AM
Comment:
fdgdfg
Title: Very nice tutorial   
Name: Janou M
Date: 2010-11-17 3:17:21 AM
Comment:
Thanks for some great code and a good, clear explanation on how to use it. This function works perfectly. If I can now just get a good GIF image that spans across my submit button .. hehehe .. it's quite long in width.
Title: Mr   
Name: Sanaj M Shaji
Date: 2010-07-01 4:21:11 PM
Comment:
Thanks a lot, you saved my 2 days work.
Title: Disable button while postback   
Name: Bryian Tan
Date: 2010-01-17 2:40:58 PM
Comment:
Jeff,

I haven't try that yet, I'll let you know once I get it to work.

Praveen ,
Nice. Initially, I was using one of the solution you mentioned in your blog. But I wanted it to work with/without the present of validation control, image button, compatible with Firefox, and display background image. And I have encapsulated all the solutions in one JavaScript.

Thanks,
Bryian Tan
Title: Disable button while postback   
Name: Praveen
Date: 2010-01-17 5:28:27 AM
Comment:
A simple solution for it is explained here. Which actually looks for the validation on server side and raise event when once the event raised. So, user can't do or send multiple request when one request is processing.
http://praveenbattula.blogspot.com/2010/01/disable-button-in-onclick-and-process.html
Title: Can we use it for delete button?   
Name: Jeff
Date: 2009-12-06 2:05:07 PM
Comment:
Hi, i have use it and it work for regular button.

but i would like to implement it into my delete buttons which required a a javascript confirm validation first. But i try something and there is no postback when i click 'yes'.

you guys have done it?
Title: A production tested alternative   
Name: sjb101
Date: 2009-11-25 4:01:10 AM
Comment:
I have used the following alternative on multiple production sites and it is an active part of my app templates now
http://encosia.com/downloads/postback-ritalin/
Title: Disable Button   
Name: Servesh
Date: 2009-11-24 11:48:03 PM
Comment:
It's working fine... and can be used for bulk upload






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-18 8:46:43 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search