Adding onserverclick event to a HtmlAnchor dynamically

霸气de小男生 提交于 2019-12-13 07:12:39

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!