codeBoy
codeBoy

Reputation: 533

OnClick Event for Anchor Tags

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

Answers (3)

IamButtman
IamButtman

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

Yuri
Yuri

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

Claudio Redi
Claudio Redi

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

Related Questions