1

I have a asp:Hyperlink with a data-attribute containing a value (a number in this case).

<asp:HyperLink ID="hypTest" href="testwebsite.com" CssClass="button-close" data-test="1" runat="server" Text="Testlink" onclick="dosomething"></asp:HyperLink>

How can I access the data attribute from this HyperLink in the codebehind when a user clicks that exact link. (there will be multiple similar links)

Also note that the onclick shown above does not work for me.
It does not access the dosomething method.

protected void dosomething()
{
    //get the data-test value
}

What would be the best way to achieve this?

Thanks in advance.

Filip Huysmans
  • 1,301
  • 1
  • 20
  • 44

1 Answers1

4

If you want the server click event - use LinkButton instead of using Hyperlink.

<asp:LinkButton ID="hypTest" CssClass="button-close" data-test="1" runat="server" Text="Testlink" onclick="dosomething"></asp:LinkButton>

For the dosomething event do it like this:

protected void dosomething(object sender, EventArgs e)
{

}

For the data attribute. Take it from the Attributes Collection.

string testData = hypTest.Attributes["data-test"]
nsgocev
  • 4,390
  • 28
  • 37
  • Is it possible to get the data attribute without knowing the ID? In case of multiple generated links – Filip Huysmans Aug 06 '14 at 12:18
  • @how you generate the multiple links ? In a repeater ? – nsgocev Aug 06 '14 at 12:19
  • @inside the repeater you no longer have the onclick event. You need to use item command - http://stackoverflow.com/questions/14861690/how-to-use-linkbutton-in-repeater-using-c-sharp-with-asp-net-4-5 – nsgocev Aug 06 '14 at 12:22