这让我很困惑,谁能解释一下?
标记:
<form id="form1" runat="server">
<asp:TextBox runat="server" ID="txtTest" />
<asp:PlaceHolder runat="server" ID="PlaceHolder1" />
<asp:Button runat="server" Text="Click" />
</form>
代码隐藏:
protected void Page_Load(object sender, EventArgs e)
{
txtTest.Text = "BBB";
PlaceHolder1.Controls.Add(new TextBox() { Text = "AAA" });
}
当我更改两个文本框中的文本,然后单击“单击”按钮时,txtTest 中的文本恢复为原始值“BBB”(在 page_load 中指定),但动态文本框保留了我刚刚输入的值(而不是“AAA”)尽管这是与另一个“硬编码”文本框同时指定的。
最佳答案
txtTest 的值在您的 Page_Load 事件中被覆盖,因此您将看不到 ViewState 值。 ViewState 值在 PreLoad 阶段加载。
动态控件的值接收 ViewState 值,因为您正在设置文本,然后将控件添加到页面。当控件被添加到页面时,它将追赶它的事件。在此追赶期间,值从 ViewState 加载,覆盖您的初始值。
Jeff Cyr 的代码不起作用,因为控件在您退出 Page_Load 之前不会播放。如果您绑定(bind)到新的 TextBox 的 Load 事件并投入几个 Response.Writes,您可以看到这一点。
protected void Page_Load(object sender, EventArgs e)
{
txtTest.Text = "BBB";
//PlaceHolder1.Controls.Add(new TextBox() { Text = "AAA" });
TextBox txt = new TextBox();
txt.Load += new EventHandler(txt_Load);
PlaceHolder1.Controls.Add(txt);
Response.Write("page load");
txt.Text = "AAA";
}
void txt_Load(object sender, EventArgs e)
{
Response.Write("textbox load");
}
关于asp.net - Viewstate - 完全困惑。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1708016/