How to disable button that causes postback in ASP.net
April 30th, 2009
You can disable a button on the client side to prevent multiple clicks by just adding an onClick function that runs on client side. You should check if page has a client side validation script and it passes first. If so, you just disable the button and call postback event.
Here is an example for the button named “btnAddcustomer”. Just paste it into Page_Load.
1 2 | Dim strDisable As String = "if (typeof(Page_ClientValidate) == 'function') {if (Page_ClientValidate() == false) { return false; }} this.value = 'Please wait...'; this.disabled = true; " & ClientScript.GetPostBackEventReference(btnAddCustomer, "") btnAddCustomer.Attributes.Add("onclick", strDisable) |
















Unfortunately there is a small problem with this code under certain circumstances, so tread with care.
In my case the page contains both validators and an updatepanel. The updatepanel contains a small portion of the page (in my case that area contains validators but doesn’t contain the button). The updatepanel is in place because it contains a control that causes an async postback (for an event other than the click of the button targeted by this code, obviously – the button is outside of the updatepanel),
Unfortunately running Page_ClientValidate breaks the updatepanel when the button is clicked. By that I mean that the first event that should fire the async postback after the button click doesn’t cause that async postback. All subsequent events do trigger the updatepanel postback until the next button click.
I haven’t found a solution to this anywhere yet, but I am still trying.
Aha! Sorted it!
There is a variable called Page_BlockSubmit that gets set as part of Page_ClientValidate. You should set this variable to false if validation fails, otherwise the next submission (by the UpdatePanel) will be, er, blocked! So the correct code (if submission of code works …) is
Dim strDisable As String = “if (typeof(Page_ClientValidate) == ‘function’) {if (Page_ClientValidate() == false) { Page_BlockSubmit = false; return false; }} this.value = ‘Please wait…’; this.disabled = true; ” & ClientScript.GetPostBackEventReference(btnAddCustomer, “”)
btnAddCustomer.Attributes.Add(”onclick”, strDisable)