Search code examples
c#htmlasp.netrunatserver

ASP.NET web form - code behind function from html control


I want to know if it's possible to call a custom function in code behind from a html element. For example ASPX file

<a id="link" CustomAttributes="Custom Value" OnClick="link_click" runat=server>link</a>

ASPX.CS file

protected void link_click(object sender, EventArgs e)
{
  response.redirect("blabla.aspx?id="+link.Attributes["CustomAttributes"]);
}

Thanks, Mattia Quaglietta

I tried the code above but it doesn't work


Solution

  • Change onclick to onserverclick and make sure 'server' is in quotation marks.

    <a id="link" CustomAttributes="Custom Value" onserverclick="link_click" runat="server">link</a>
    
    protected void link_click(object sender, EventArgs e) {
      response.redirect($"blabla.aspx?id={link.Attributes["CustomAttributes"]}");
    }
    

    You can find more info here: https://learn.microsoft.com/en-us/previous-versions/dotnet/netframework-4.0/8ff86hxd(v=vs.100)