问题
I've got a page and would like to append the onserverclick event to my existing HtmlAnchor.
In the design view I am first adding the control
<a runat="server" id="lnkFre" title="FR" onclick="document.getElementById('ctl00_hidLang').value='en-US';"><span>Français</span> </a>
I tried like this.
HtmlAnchor lnkFre = FindControl("lnkFre") as HtmlAnchor;
lnkFre.ServerClick += new EventHandler(lnkLang_Click);
Here the lnkLang_Click is an event in a class which is accessible from this page.
But at runtime it is not being added.
I wish to have something like this.
<a runat="server" id="lnkFre" title="FR" onserverclick="lnkLang_Click" onclick="document.getElementById('ctl00_hidLang').value='fr-BE';"><span>Français</span> </a>
Is this possible in this way? Or kindly suggest me another method.
Thanks a lot
回答1:
This works for me:
HTML
<a href="#A" runat="server" id="MyAnchor" onclick="alert('test');return true;">A</a>
Code Behind
protected void Page_Load(object sender, EventArgs e)
{
HtmlAnchor lnkFre = MyAnchor as HtmlAnchor;
lnkFre.ServerClick += new EventHandler(lnkFre_ServerClick);
}
void lnkFre_ServerClick(object sender, EventArgs e)
{
throw new NotImplementedException();
}
You obviously won't be able to see the markup at runtime as the event is being bound dynamically but it will call the server click event.
Please also note the return(true);
at the end of the onclick event. This is necessary for the server click to also fire.
来源:https://stackoverflow.com/questions/18744126/adding-onserverclick-event-to-a-htmlanchor-dynamically