我需要为查询的每一行创建一个“投票”按钮。因此我必须动态地做。但是,出于某种原因,当我动态添加按钮并在page_init()
方法中创建它的事件处理程序时 - 按钮已创建,但单击时事件未触发。
这是我正在使用的代码。我还尝试使用page_load()
代替page_init()
,但结果是一样的。
protected void Page_Init(object sender, EventArgs e)
{
if (Session["user"] == null) Response.Redirect("../login/Login.aspx", true);
string id = Request.QueryString["iss"];
if (id == null || id == "") Response.Redirect("../Default.aspx");
SqlRow issue = Database.Query("SELECT * FROM issues WHERE id=?", id)[0];
SqlRes options = Database.Query("SELECT * FROM options WHERE issue=?", id);
issueTitle.Title = issue["title"].ToString();
issueText.InnerText = issue["issue"].ToString();
if (options.Count == 0) return;
int w = 90 / options.Count;
foreach(SqlRow option in options)
{
bool voted = Database.Query("SELECT * FROM options_votes WHERE opt=? AND userid=?", option["Id"], Session["user"]).Count>0;
Part p = new Part
{
W = w,
};
var title = new HtmlGenericControl("h2");
title.Attributes["class"] = "dark";
title.InnerText = option["title"].ToString();
p.Controls.Add(title);
Button vote = new Button
{
Text = "VOTE",
};
vote.Click += (se, ev) =>
{
bool nvoted = Database.Query("SELECT * FROM options_votes WHERE opt=? AND userid=?", option["Id"], Session["user"]).Count > 0;
if (nvoted)
{
Database.Query("DELETE FROM options_votes WHERE opt=? AND userid=?", option["Id"], Session["user"]);
vote.BackColor = Color.FromArgb(0x17, 0x25, 0x2a);
}
else
{
Database.Query("INSERT INTO options_votes (opt, userid) VALUES (?, ?)", option["Id"], Session["user"]);
vote.BackColor = Color.Gray;
}
};
if (voted) vote.BackColor = Color.Gray;
vote.Attributes["class"] = "vote";
p.Controls.Add(vote);
issueTitle.Controls.Add(p);
}
}
类似问题的其他答案说用visible=false
添加按钮,但在我的情况下,我无法在.aspx页面中添加按钮,它必须在代码隐藏中。
答案 0 :(得分:0)
我找到了一个解决方案:
通过向按钮添加UseSubmitBehavior="false"
,我设法让点击事件有效。