【发布时间】:2018-04-23 20:04:42
【问题描述】:
我在 c# 代码隐藏中创建了一个按钮,并尝试向它添加事件侦听器,但问题是如果我使用:
{
HtmlGenericControl dodaj = new HtmlGenericControl("button");
dodaj.InnerText = "something";
dodaj.Attributes.Add("runat", "server");
dodaj.Attributes.Add("type", "submit");
dodaj.Attributes.Add("onclick","addKosarica");
newDivInfo.Controls.Add(dodaj);
sadrzaj.Controls.Add(newDivInfo);
this.Controls.Add(sadrzaj);
}
protected void addKosarica(object sender, EventArgs e)
{
Response.Redirect("www.google.com"); //just to see if it triggers
}
我明白了:
"Uncaught ReferenceError: addKosarica 未定义在 HTMLButtonElement.onclick"
尝试谷歌搜索错误,它与javascript有关......
然后在谷歌上搜索了一些之后,我尝试了:
{
Button dodaj = new Button;
dodaj.Text = "something";
dodaj.Click += new EventHandler("addKosarica");
newDivInfo.Controls.Add(dodaj);
sadrzaj.Controls.Add(newDivInfo);
this.Controls.Add(sadrzaj);
}
protected void addKosarica(object sender, EventArgs e)
{
Response.Redirect("www.google.com");//just to see if it triggers
}
我得到了
“'Button'类型的控件'ctl07'必须放在表单标签内 使用 runat=server。”
这是我的 aspx 代码:
<%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="11001.aspx.cs" Inherits="_11001" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
</asp:Content>
(它并不多,因为我动态添加了所有内容,并且除了按钮 onclick 处理程序之外一切正常......)
拜托,谁能告诉我如何使它工作......
编辑: sadrzaj 是一个 div,其中包含我要添加的所有这些元素。 我将它们添加到从 Page_Load() 调用的函数中
【问题讨论】:
-
您的
form标签在哪里?您的母版页上有一个吗?正如错误所说,您的按钮需要在表单标签内。 -
@CalC 表单标签在母版页中,在正文标签内