Decrease Font Size
Increase Font Size
   BLOG

Disable an ASP.NET button during PostBack with AJAX loading background image

by bryian 13. August 2009 15:57

Disable submit button after user click | Disabling an ASP.NET Button when Clicked | Disable an ASP.NET button after clicking | Page_IsValid is undefined - JavaScript error message

Disable an ASP.NET button during PostBack with AJAX loading background image

 

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

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

 Projext structure
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="JScript.js"></script> 

In this 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 = DateTime.Now.ToLongTimeString();
    }


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

 on click Demo 1 Output

Demo 2 – With Validation Control

Here is the output from Default2.aspx

 Demo 2 aspx page

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

 Demo 2 aspx page 2

Here is the content of the new JavaScript with comments– Jscript2.js 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) to enable the button onunload for browser other than IE

10/12/2009 - I have updated the JavaScript(JScript2) to prevent double validation.

11/14/2009 - Fix bug mentioned by CodeProject user, prodriguez13. The JavaScript will throw an error when the control to validate is not visible. To remedy this problem, I have added DisableValidators function and trigger it on onload event. This function is responsible to disable all the validators where controltovalidate is null.
* I have received several requests on getting this script to work with Image button. I managed to put together a solution for it. Let me know if you find any bugs.
* Tested on IE 7.0/8.0, FireFox, image is not showing on Google Chrome, maybe someone can shed some light on this.

   
function ResetToDefault(btn, oldValue) {
    btn.disabled = false;
    btn.value = oldValue;
}
//browser properties
var 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.html
function 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 7
        if (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 IE
function EnableOnUnload(btn, btnText) {
    if (!Browser.isIE()) {
        window.onunload = function() {
            ResetToDefault(btn, btnText);
        };
    }
}

//check if the validator have any control to validate
function 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 present
    if (HasPageValidators()) {

        Page_IsValid = null;

        //http://sandblogaspnet.blogspot.com/2009/04/calling-validator-controls-from.html
        //double check, if validator not null
        if (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 valid
                        ResetToDefault(btn, oldValue); //break;
                    }
                }
            }

            //   else { //if valid
            var isValidationOk = Page_IsValid;

            alert('isValidationOk ' + isValidationOk);

            EnableOnUnload(btn, btn.value);
            if (isValidationOk !== null) {
                if (isValidationOk) {
                    SetImage(btn);
                    __doPostBack(btnID, '');
                    // break;
                }
                else { //page not valid
                    btn.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 = null
function DisableValidators() {
    //this will get rid of the Page_Validators is undefined error
    if (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 using the new JavaScript

 Demo 2 aspx page 2  Demo 2 aspx output 3
 Demo 2 aspx output 4

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.2

Watch this Script in action

Comments

8/17/2009 2:03:45 PM #

trackback

Disable an ASP.NET button during PostBack with AJAX loading background

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com

9/17/2009 10:08:06 PM #

Интернет Маркетинг

Thanks mate!I was looking for that solution nearly all day!I love your blog,awesome!!!
Can I copy this article on my blog?If,yes we can exchange useful articles in the future?

Интернет Маркетинг

10/22/2009 10:33:57 PM #

best

best

best United Kingdom

10/23/2009 10:01:18 PM #

Stephen Dale

You can also use the following in the code behind without javascript.

var clickHandler12 =
                    string.Format(
                        "document.body.style.cursor = 'wait'; this.value='Please Wait...'; this.disabled = true; {0};",
                        ClientScript.GetPostBackEventReference(_btnIncludeWriteGroup, string.Empty));

_btnSomeButton.Attributes.Add("onclick", clickHandler12);

Stephen Dale Denmark

10/24/2009 4:07:40 AM #

Thanigainathan

Hi,

I expected somewhat more than you have written. I thought you are going to tell about Ajax.
Can you please throw some light on this stuff with Ajax.

Thanks,
Thani

Thanigainathan India

10/25/2009 6:27:04 AM #

Ravi

can we do the same for image button....

Thanks
Ravi
mcamail2002@gmail.com

Ravi India

10/25/2009 8:05:12 AM #

trackback

Social comments and analytics for this post

This post was mentioned on Twitter by michaeljbyers: Disable an ASP.NET button during PostBack with AJAX loading background image http://bit.ly/fEVuM

uberVU - social comments

10/26/2009 4:53:07 AM #

Ravi

No i dont have as sach code but im using image button in my project.

Ravi India

11/2/2009 10:11:17 PM #

Adeel Alvi


There is one issue while using your code , as i have some RequiredFieldValidator which are disabled on PageLoad and will enable on some option clicked by user , but after using your code it asked for those RequiredFieldValidator as well that are disabled on Page Load.

Adeel Alvi

11/6/2009 1:35:10 PM #

bryian

Hello, I have updated the script and source code.

bryian United States

11/18/2009 2:15:38 PM #

Outsourcing

I was just thinking about Disable an ASP.NET button during PostBack with AJAX loading background image and you have really helped out. Thanks!

Outsourcing United States

11/30/2009 9:15:50 PM #

Hopeto

Thanx for the article. i was searching the same functionality for an image button. will try it out.

Hopeto India

12/1/2009 12:09:24 AM #

ditte traslochi milano

That's great, I never thought about Disable an ASP.NET button during PostBack with AJAX loading background image like that before.

ditte traslochi milano United States

12/8/2009 2:46:00 PM #

Craft Shows

That's great, I never knew before this blog.

Craft Shows United States

12/8/2009 6:53:07 PM #

Craft Fairs

That's really very nice blog, I am impressed.

Craft Fairs United States

1/16/2010 9:40:27 PM #

Deals

love this post.
Thanks frenz.
dont stop posting!

Deals United Kingdom

2/3/2010 2:11:11 AM #

Cross Stitching

Wow, thanks for a great tutorial on disabling the asp.net button with ajax during postback. Very useful and very detailed.

Cross Stitching United States

2/3/2010 3:41:57 PM #

P90X

I just stumbled upon your blog and wanted to say that I have really enjoyed reading your blog posts.
I will catch up your updates in future.
A

P90X United States

2/3/2010 5:40:38 PM #

Internet Marketing Italy

This is the good step u have taken. Thanks for writing this, its clear you have spent a good amount of time on your sites development.

Internet Marketing Italy United States

2/7/2010 8:41:20 PM #

NOD32

Hey saw your post today & bryianI must say you have done a great job in understanding the basics of this topic & working on the updates. I am looking forward to more articles from you on the same topic.

NOD32 United States

2/9/2010 9:45:07 PM #

ESET

Thanks a lot for the post. Your views are rally insightful and am looking forward to read more from you. Thanks

ESET United States

2/16/2010 1:48:50 PM #

Statistics Help

Great work dude, u gave nice post to us. Thanks for spending the time to discuss this, I feel strongly about it and love learning more on this topic.

Statistics Help United States

2/16/2010 5:36:28 PM #

Kerala Tourism

This is a great and very valuable information about Disable an ASP.NET button during PostBack with AJAX loading background image. Thank you very much for sharing this information with us.

Thanks.

Kerala Tourism India

3/1/2010 1:21:24 AM #

stell

from this article, i can undestand what is AJAX and ASP.net. Actually, i don't undestand before

stell United States

Add comment


(Will show your Gravatar icon)

  Country flag

Click to change captcha
biuquote
  • Comment
  • Preview
Loading