Friday, July 30, 2010

Disabling an ASP.NET button when clicked

Hi all,

In one of my projects, I had an requirement where when a user browse a file via "FileUpload" control and hit the "Submit" button then button should be disabled. Moreover, I thought besides disabling the button I could display an image as well so that the user interface is more interactive. I have developed a custom user control that is hosted in an application page.

After "Googling" for this requirement, I found a couple sample but most of them used "HTML" input controls. But, I wanted an <asp:Button> control. Finally, I got the trick. When we double click on the "Submit" button, then an event handler has been generated with a "OnClick" server side code. We can leverage on "OnClientClick" property that executes a client side script. Besides this "OnClientClick" property we need to implement our own custom javascript that disables the button. UseSubmitBehavior="false" - Indicates that the button control should use the ASP.NET postback mechanism instead of the client browser's submit mechanism (UseSubmitBehavior property).

 <script type="text/javascript" language="javascript">
        function disableBtn(btnID, newText) {

            var btn = document.getElementById(btnID);
            btn.disabled = true;
            btn.value = newText;

            //Setting Image properties 
   = 'url(/_layouts/images/projectName/ajax-loader.gif)';
   = 'no-repeat';
   = 'center';

<asp:button id="btnOne" tabIndex="0" 
                    Runat="server" Text="Submit"
                    OnClientClick="disableBtn(, 'Submitting...')" 
                    UseSubmitBehavior="false" /> 
This code works perfectly on Firefox but image loading part did not work. 
There is a very useful tip from  4guysfromrolla where page "Freeze" on the form submission. 


1) ASPAlliance  
2) 4GuysfromRolla

No comments:

How to: Use cascading drop-down lists in PowerApps

Hi all, Using cascading dropdown, users can easily fill the forms by selecting drop-down values dependent on values from another dro...