OnClick Event for Anchor Tags

20,705

Solution 1

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.

Solution 2

yes, you can, but you need to add onserverclick attribute or use asp Hyperlink control

  <a id="AnchorButton"
     onserverclick="AnchorButton_Click"
     runat="server">

Solution 3

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*/
    }
Share:
20,705
codeBoy
Author by

codeBoy

Updated on June 21, 2020

Comments

  • codeBoy
    codeBoy almost 4 years

    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?

  • ZooZ
    ZooZ about 3 years
    Simple and neat! Thank you