Thursday, June 7, 2012

Disable Button While Processing a Request in Asp.Net

I have been looking into a problem of disabling a button when user clicked to prevent the multiple clicks. Finally I got a solution.

I tried to disable the button in client side by writing a piece of javascript code, but it doesnt work. If we want this in client side, we need to do all the validations and all other client side stuffs manually.

This is a tricky logic, if you have eny better idea please share.
Add the following html code.

<asp:Button ID="btnSearch" CssClass="button" runat="server" Text="Search" 

onclick="btnSearch_Click" />

<div style="display:none">

<asp:Button ID="btnSearch1" CssClass="button" runat="server" Text="Search" 

onclick="btnSearch1_Click" />

</div>



Add the following javascript in your aspx page
<script type= "text/javascript">

function postSearchData() {

jQuery(document).ready(function () {

jQuery("#btnSearch1").trigger("click");

});

}

</script>



Add the Buttons event handlers
protected void btnSearch_Click(object sender, EventArgs e)

{

btnSearch.Enabled = false;

Page.ClientScript.RegisterClientScriptBlock(typeof(Label), "postback", "postSearchData();", true); 

}

protected void btnSearch1_Click(object sender, EventArgs e)

{

System.Threading.Thread.Sleep(5000);// remove this line
// do your operations here.
btnSearch.Enabled = true;

}



In the above example btnSearch is associateed with all validation controls and it does the validations. When user clicks on it it cause a postback and disable it, a piece of javascript code is written to the page after the postback to automatically fire the btnSearch1 button's click event. btnSearch1 will remain always hidden.

Hope this will help you, do not hesitate to share your comments.

1 comment:

Basil Downs said...

Another concept is to just throw layer the button after it is visited so that it basically disappears to the customer.