How to disable an ASP.NET linkbutton when clicked
- by Jeff Widmer
Scenario: User clicks a LinkButton in your ASP.NET page and you want to disable it immediately using javascript so that the user cannot accidentally click it again. I wrote about disabling a regular submit button here: How to disable an ASP.NET button when clicked. But the method described in the other blog post does not work for disabling a LinkButton. This is because the Post Back Event Reference is called using a snippet of javascript from within the href of the anchor tag: <a id="MyContrl_MyButton" href="javascript:__doPostBack('MyContrl$MyButton','')">My Button</a> If you try to add an onclick event to disable the button, even though the button will become disabled, the href will still be allowed to be clicked multiple times (causing duplicate form submissions). To get around this, in addition to disabling the button in the onclick javascript, you can set the href to “#” to prevent it from doing anything on the page. You can add this to the LinkButton from your code behind like this: MyButton.Attributes.Add("onclick", "this.href='#';this.disabled=true;" + Page.ClientScript.GetPostBackEventReference(MyButton, "").ToString()); This code adds javascript to set the href to “#” and then disable the button in the onclick event of the LinkButton by appending to the Attributes collection of the ASP.NET LinkButton control. Then the Post Back Event Reference for the button is called right after disabling the button. Make sure you add the Post Back Event Reference to the onclick because now that you are changing the anchor href, the button still needs to perform the original postback. With the code above now the button onclick event will look something like this: onclick="this.href='#';this.disabled=true;__doPostBack('MyContrl$MyButton','');" The anchor href is set to “#”, the linkbutton is disabled, AND then the button post back method is called. Technorati Tags: ASP.NET LinkButton