【发布时间】:2010-10-13 04:24:36
【问题描述】:
ASP.NET 页面的 ViewState 似乎无法跟上动态删除的控件及其中的值。
我们以下面的代码为例:
ASPX:
<form id="form1" runat="server">
<div>
<asp:Panel runat="server" ID="controls" />
</div>
</form>
CS:
protected void Page_Init(object sender, EventArgs e) {
Button b = new Button();
b.Text = "Add";
b.Click +=new EventHandler(buttonOnClick);
form1.Controls.Add(b);
Button postback = new Button();
postback.Text = "Postback";
form1.Controls.Add(postback);
}
protected void Page_Load(object sender, EventArgs e) {
if (ViewState["controls"] != null) {
for (int i = 0; i < int.Parse(ViewState["controls"].ToString()); i++) {
controls.Controls.Add(new TextBox());
Button remove = new Button();
remove.Text = "Remove";
remove.Click +=new EventHandler(removeOnClick);
controls.Controls.Add(remove);
controls.Controls.Add(new LiteralControl("<br />"));
}
}
}
protected void removeOnClick(object sender, EventArgs e) {
Control s = sender as Control;
//A hacky way to remove the components around the button and the button itself
s.Parent.Controls.Remove(s.Parent.Controls[s.Parent.Controls.IndexOf(s) + 1]);
s.Parent.Controls.Remove(s.Parent.Controls[s.Parent.Controls.IndexOf(s) - 1]);
s.Parent.Controls.Remove(s.Parent.Controls[s.Parent.Controls.IndexOf(s)]);
ViewState["controls"] = (int.Parse(ViewState["controls"].ToString()) - 1).ToString();
}
protected void buttonOnClick(object sender, EventArgs e) {
if (ViewState["controls"] == null)
ViewState["controls"] = "1";
else
ViewState["controls"] = (int.Parse(ViewState["controls"].ToString()) + 1).ToString();
controls.Controls.Add(new TextBox());
}
然后,假设您创建 4 个控件并插入以下值:
[ 1 ] [ 2 ] [ 3 ] [ 4 ]
我们要删除第二个控件;删除第二个控件后 输出是:
[ 1 ] [ 3 ] [ 4 ]
这就是我们想要的。不幸的是,在随后的 PostBack 中,列表 变成:
[ 1 ] [ ] [ 3 ]
所以,我的问题是,为什么会发生这种情况?据我所知,ViewState 应该保存与索引相关的控件属性,而不是实际的控件。
【问题讨论】:
标签: asp.net dynamic controls viewstate