单击动态添加按钮时在代码后面触发事件



我正在尝试使用 HtmlTextWriter 从动态添加的按钮调用btn_Click。但它不会触发。我无法在代码后面向按钮添加事件处理程序,因为它不是 ASP.NET 按钮。

    protected void btn_Click(object sender, EventArgs e)
    {
         WindowJavaScript.Alert("halo");
    }
protected void PageLoad(object sender, EventArgs e)
{
    //some checking hee to determine whether user is admin or not.
    if(isAdmin)
    {
         writer.AddAttribute(HtmlTextWriterAttribute.Class, "nav navbar-nav navbar-right");
         writer.RenderBeginTag(HtmlTextWriterTag.Ul);
         writer.RenderBeginTag(HtmlTextWriterTag.Li);
         writer.AddAttribute(HtmlTextWriterAttribute.Class, "navbar-brand");
         writer.AddAttribute("runat", "server");
         writer.AddAttribute(HtmlTextWriterAttribute.Id, "admin_B");
         writer.AddAttribute("onserverclick", "btn_Click");
         writer.RenderBeginTag(HtmlTextWriterTag.Button);
         writer.Write("Admin");
         writer.RenderEndTag();
         writer.RenderEndTag();
         writer.RenderEndTag();
    }
}

尝试将您的代码转换为将属性映射到按钮时,我注意到您有writer.AddAttribute("onserverclick", "btn_Click"),您应该有writer.AddAttribute("onclick", "btn_Click").

此外,还可以通过在页面中将按钮

追加到页面中的另一个控件来动态添加按钮。

protected void PageLoad(object sender, EventArgs e)
{
        //some checking hee to determine whether user is admin or not.
        if (isAdmin)
        {
            var btnAdmin = new Button();
            btnAdmin.Click += btn_Click;
            btnAdmin.Text = "Admin";
            btnAdmin.ID = "admin_B";
            otherControl.Controls.Add(btnAdmin); // you need to create otherControl on page
        }
}

相关内容

  • 没有找到相关文章

最新更新