我正在尝试使用btn_Click
从动态添加的按钮中调用HtmlTextWriter
。但它不会触发。我无法在代码中添加事件处理程序,因为它不是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();
}
}
答案 0 :(得分:1)
尝试将代码转换为地图属性到按钮时我注意到您有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
}
}