Monday, December 8, 2008

Disable button after clicked once

We were fond of people(testing) who tries to click the button twice or thrice when It was performing some operation which may yield the wrong result or does unnecessary postpack to the page.
So we can achieve this by disabling the button in the OnClientClick event of the button using javascript. But the problem is after disabling the button, it doesn't invoke the server click event even though we return true in the client event.

function Disable(t) {
        if( t != null)
        {
            t.disabled = true;
            t.value = 'Processing...';
            return true;
        }
        return false;
    }

        asp:Button ID="Button1" runat="server" OnClientClick="return Disable(this)" onclick="Button1_Click" Text="Button" 

Therefore ASP.Net 2.0 has a property called "UseSubmitBehavior". 

Gets or sets a value indicating whether the Button control uses the client browser's submit mechanism or the ASP.NET postback mechanism. Default value is true. False appends the code for _doPostBack(this). Check with ViewSource after setting the value to False.

Therefore setting this value to false triggers the server event. The below code works fine.

        asp:Button ID="Button1" runat="server" UseSubmitBehavior="false" OnClientClick="this.disabled='true';this.value='processing...';" onclick="Button1_Click" Text="Button" 

        



No comments: