我有以下很简单的代码
<asp:ScriptManager ID="ScriptManager1" runat="server"> </asp:ScriptManager> <asp:UpdatePanel ID="UpdatePanel1" runat="server"> <ContentTemplate> <asp:PlaceHolder ID="PlaceHolder1" runat="server"> </asp:PlaceHolder> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> </ContentTemplate> </asp:UpdatePanel>
和代码
protected void Button1_Click(object sender,EventArgs e) { Literal literal = new Literal(); literal.Text = DateTime.Now.ToString(); literal.ID = DateTime.Now.Ticks.ToString(); // These both work fine the first time the button is clicked // but the second time nothing is added. UpdatePanel1.ContentTemplateContainer.Controls.Add(literal); PlaceHolder1.Controls.Add(literal); }
解决方法
在asp.net中,ASPX文件中的控件会自动生成每个回发.您创建的控件不在ASPX代码中,因此框架不会为您创建它们.第一次执行Button1_Click方法时,您可以向页面添加一个额外的控件.您第二次执行Button1_Click方法时,您正在另一个帖子,第一个额外的按钮已被忘记.因此,回发的结果是你再次获得一个额外的按钮.
这将在您每次单击按钮时创建一个额外的控件(虽然每次按下按钮时都会更新时间戳,因为重新创建控件)
protected void Button1_Click(object sender,EventArgs e) { int count = 0; if (ViewState["ButtonCount"] != null) { count = (int)ViewState["ButtonCount"]; } count++; ViewState["ButtonCount"] = count; for (int i = 0; i < count; i++) { Literal literal = new Literal(); literal.Text = DateTime.Now.ToString(); literal.ID = DateTime.Now.Ticks.ToString(); UpdatePanel1.ContentTemplateContainer.Controls.Add(literal); PlaceHolder1.Controls.Add(literal); } }