ASP.NET使用动态控件生成OnServerClick

时间:2015-12-03 10:10:42

标签: asp.net

我正在生成一个像这样的“HtmlAnchor”控件:

<li>
    <a id=\"AnchorButton\" onserverclick=\"HtmlAnchor_Click\" runat=\"server\">&lt;&lt;</a>
</li>

我将偶数链接到Page_Load中的控件:

System.Web.UI.HtmlControls.HtmlAnchor AnchorButton = new System.Web.UI.HtmlControls.HtmlAnchor();
AnchorButton.Visible = false;
AnchorButton.ServerClick += new System.EventHandler(this.HtmlAnchor_Click);

我还定义了“HtmlAnchor_Click”方法。 当我点击HtmlAnchor控件时,事件没有触发。

如何触发此事件?

2 个答案:

答案 0 :(得分:0)

&lt;%@ Page EnableEventValidation =“false”

<ul>
    <li>
        <a id="AnchorButton" onserverclick="Button1_Click" runat="server">&lt;&lt;</a>
    </li>
</ul>
<div>
    <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</div>

代码隐藏:

void MyMethod()
{
    System.Web.UI.HtmlControls.HtmlAnchor AnchorButton = new System.Web.UI.HtmlControls.HtmlAnchor();
    AnchorButton.Visible = false;
    AnchorButton.ServerClick += new System.EventHandler(this.Button1_Click);  
}

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Write("CLICK");
}

答案 1 :(得分:0)

您可以在aspx页面中保留一个面板控件(System.Web.UI.WebControls.Panel),然后从服务器端向面板动态添加控件。

例如:

System.Web.UI.HtmlControls.HtmlAnchor AnchorButton = new System.Web.UI.HtmlControls.HtmlAnchor();
AnchorButton.Visible = false;
AnchorButton.ServerClick += new System.EventHandler(HtmlAnchor_Click);
panel.Controls.Add(AnchorButton);