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 
            btn.style.backgroundImage = 'url(/_layouts/images/projectName/ajax-loader.gif)';
            btn.style.backgroundRepeat = 'no-repeat';
            btn.style.backgroundPosition = 'center';

        }
    </script>
 
<asp:button id="btnOne" tabIndex="0" 
                    Runat="server" Text="Submit"
                    onclick="btnOne_Click" 
                    OnClientClick="disableBtn(this.id, '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. 

Cheers, 
--aaroh 

References: 
1) ASPAlliance  
2) 4GuysfromRolla


No comments:

Low Code Reimagined with AI + Copilot Pitch Deck - Copy Copilot day (Virtual) - 2023

 Hi All,  I presneded a session at Pune UG on Low Code Reimagined with AI + Copilot Pitch Deck.  Video is at this address  https://www.youtu...