Canceling Linkbutton Clicked Event when the User tries to click it Again

There is many reasons to prevent that , like preventing mutiple Database Calls , Or Even Preventing them from submitting the form twice and so save the bandwidth and server resources .

this is a one solution for that Issue ,

Use a hiddenField control to remeber the Click counts ,and when the Linkbutton clicked you check to see if the click counts >0 ,

 if yes then you will cancel the click event ,

To Accomplish this , Add a hiddenField Server control to your page as follows :

<asp:HiddenField ID="HiddenField1" runat="server" Value="0" />
Now Register Onclick Attribute for the Linkbutton , in page load add this code :
 If Not IsPostBack Then
   LinkButton1.Attributes("onclick") = String.Format("javascript:var Count = document.getElementById('{0}');
 if (Count.value>0) return false ;Count.value =Count.value+1; ", HiddenField1.ClientID)
 End If


How To Test that :


Add the hidden field and register the Onclick attribute as mentioned ,
Now click the LinkButton for the first time , the form must be submitted (postback must occured)
Try to click the LinkButton for the second time, you will notice that there is no postback happened .


Regards,
Anas ghanem

Published Sunday, March 09, 2008 5:45 PM by anas
Filed under:

Comments

# re: Canceling Linkbutton Clicked Event when the User tries to click it Again

Sunday, March 09, 2008 4:51 PM by Maciej Kuczara (ABB)

Why not disable button after click?

# re: Canceling Linkbutton Clicked Event when the User tries to click it Again

Sunday, March 09, 2008 10:03 PM by Will Green

Stop using LinkButtons! LinkButtons are an evil, frankenstein bastardization of HTML. Links were only ever meant to LINK to other documents; that is issue GET requests when clicked. GET requests are never supposed to change the state of anything.

Buttons, on the other hand, ARE designed for state-changing (POST, PUT, DELETE) requests.

Also, keep this in mind: Lets say you have a search results page, and you put those results in a GridView, and you enable paging. Google, Yahoo, Live Search, etc. will NEVER be able to page through your results, because the paging control is a series of LinkButtons. That is, they are HTML anchors whose HREF attribute is a JavaScript function. Search engines cannot crawl JavaScript functions.

Simply using a LinkButton control because you want a PostBack control that looks like a link is, IMO, a very poor reason to choose a LinkButton. You could accomplish the same feat by using an HTML button with a runat=server attribute, and use CSS to make it look like a Link. No bastardization of HTML, the DOM, or JavaScript required.

More work? Possibly. However, just because Microsoft does it doesn't make it the right way to do it.

Leave a Comment

(required) 
(required) 
(optional)
(required)