asp.net 按钮 Onclick 事件未触发其代码隐藏函数

本文关键字:代码 隐藏 函数 net 按钮 Onclick 事件 asp | 更新日期: 2023-09-27 18:36:57

在页面中使用asp按钮 asp.net。在代码隐藏中将此按钮呈现为 html 字符串并分配给div。

<asp:ImageButton ID="ProImg" runat="server" CssClass="Photo" ImageUrl="~/images/ProfilePage/pic.jpg"
                    ImageAlign="Middle" OnClick="ProImg_Click" />

渲染方案为

Control MyApps = tabsUL.FindControl("MyApp");
string MyAppshtml = RenderControl(MyApps);
outerTabInfo.InnerHtml =  MyAppTxt;

渲染控制功能是

private string RenderControl(Control control)
{
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter writer = new HtmlTextWriter(sw);
    control.RenderControl(writer);
    return sb.ToString();
}

但它实际上并没有触发ProgImg_Click功能。该函数是

protected void ProImg_Click(object sender, EventArgs e)
{
    //code process
}

我怎么能做到呢?提前致谢

asp.net 按钮 Onclick 事件未触发其代码隐藏函数

您需要以编程方式附加事件

private string RenderControl(Control control)
{
    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    HtmlTextWriter writer = new HtmlTextWriter(sw);
    if(control.Id=="ProImg"){
      control.Click += new System.EventHandler(this.ProImg_Click);
     }
    control.RenderControl(writer);
    return sb.ToString();
}