Thursday, September 20, 2012

How to quickly disable an asp.net button from client side



usually we will create a JavaScript function to handle the client side click event.

something like the following

In Client Side

 function disableButton(buttnId) {
            document.getElementsByName(buttnId)[0].disabled = true;
 }


In Server Side
   
buttonControl.Attributes.Add("onclick", "this.disabled=true;");


In Design Mode
However we can do it very quick in the design mode, set its disabled attribute to be true at
onClientClick event.

OnClientClick="this.disabled=true;"


<asp:Button runat="server" ID="btnSubmit" Text="Submit Data" 
OnClick="btnSubmit_Click" Enabled="false" OnClientClick="this.disabled=true;" /> 
 
I had found one serious issue during this implementation. 
though i can disable the button to prevent the user double click on it.
However the server side event had been disabled as well. i believe when i disabled
the button in the client side. when page was not pushed back to the server. 
then it will not execute the server side click event and force the page to refresh.
 
we must manually refresh the page on the client side. 
the line of code will hook up the _doPostBack() event on the button control.
btnSubmit.Page.ClientScript.GetPostBackEventReference(btnSubmit,"") 

  protected void Page_Load(object sender, EventArgs e)
  {
     if (!IsPostBack)
     {
         btnSubmit.Attributes.Add("onclick""javascript:" +btnSubmit.ClientID +".disabled=true;" 
             +btnSubmit.Page.ClientScript.GetPostBackEventReference(btnSubmit,""));
     }
 }
 
when you click on the button, the exception will thrown immediately
the Error Message is "Microsoft JScript runtime error: The value of the property '__doPostBack' 
is null or undefined, not a Function object"
you will find the solution from this link. Ensure that __doPostBack() function is implemented on the page  

 

No comments:

Post a Comment