Reputation: 533
Is there an onClick
event for anchor tags? I have the following line of code:
<li><a href="#" runat="server">Logout</a></li>
When the user clicks the logout text I want it to fire some code that would be in a method like this:
protected void btnLogout_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Session.Abandon();
}
What is the best practice at doing this in an anchor tag?
Upvotes: 4
Views: 26914
Reputation: 347
You can do one thing, provide ID to the link button:
<a runat="server" id="anchorTagButton">Click Me!!</a>
In the asp.net page load
anchorTagButton.ServerClick += new EventHandler(anchorTag_Click);
and finally
protected void anchorTag_Click(object sender, EventArgs e)
{
/*do stuff here*/
}
Upvotes: 3
Reputation: 2900
yes, you can, but you need to add onserverclick attribute or use asp Hyperlink control
<a id="AnchorButton"
onserverclick="AnchorButton_Click"
runat="server">
Upvotes: 5
Reputation: 68400
Instead of standard html anchor tag, use the LinkButton
for this. It provides the functionality you're looking for.
Here you have a sample
<asp:LinkButton id="btnLogout" Text="Logout" OnClick="btnLogout_Click" runat="server"/>
It renders to an HTML anchor so visually it's the same as your code.
Upvotes: 9