大多数 ASP.NET 的开发者认为 ASP.NET 的 ViewState 对象负责保持类似 TextBox 文本控件的值,因而这些值甚至在回传后还被保留着。但是这却不是这么回事。
我将用一个例子来解释。你可以下载项目文件(http://www.codeproject.com/aspnet/ViewState/ViewState.zip),建立一个名为 ViewState 的虚拟目录,并运行这个应用程序。让我们从一个 C# 语言的 Web 项目开始。
建立一个新的 ASP.NET Web 应用,然后在 WebForm 上放置以下控件:
放一个服务器 TextBox 控件,一个 HTML 服务器文本控件(带 runat=server 属性的普通 HTML 输入框),一个普通的 HTML 输入控件,和一个服务器端 Label 控件。4 个控件命名如下:
txtWebServerTest
txtHtmlServerTest
txtHtmlTest
lblTest
设置上边3个文本框的 Text 或 Value 属性为“Initial Text”。设置下边Label控件的 Text 属性为“Initial Label Value”。
设置第一个和最后一个控件的 EnableViewState 属性为 false。
在所有控件的下边,放置 2 个按钮控件(Button),分别设置它们的 Text 属性为“Change Label’s Text”和“Postback to Server”。在第一个按钮的点击事件里写入以下代码:
private void btnChangeLabel_Click(object sender, System.EventArgs e)
{
lblTest.Text = "Label's Text Changed";
}
在第二个按钮的点击事件里不写任何代码。它仅仅提交页面到服务器。
现在运行这个应用。你可以看到控件上你预先设置的初始化文本。
现在,改变所有文本框的文本,把他们设置为字符串“Changed Text”。再点击提交到服务器的按钮。可以看到前边的 2 个文本框保持了它们的值,尽管它们的 ViewState 属性被设置为 false。但是下一个文本框(简单的 HTML 输入控件),当页面被重新加载时,丢失了修改了的值。
大多数开发者可能期望所有的 3 个文本框都丢失它们更改了的值(“Changed Text”),并且在页面重新后,他们期望字符串“Initial Value”被重新写回到文本框中,因为我们已经把 ViewState 属性设置为 disabled 了。
这种行为的原因是,ViewState 是不负责存储诸如 TextBoxes, dropdowns, CheckBoxList 等这些继承自 IPostBackDataHandler 接口的控件的更改了的值的。在 Page_Init() 事件后,有个称为 LoadViewState 的事件,在这里 Page 类从隐藏的域 __VIEWSTATE 中为诸如 ViewState 属性为 enabled 的 Label 控件装载值。然后 LoadPostBackData 事件被出发,在这里 Page 类从 HTTP 提交头(POST headers)中装载继承自 IPostBackDataHandler 接口的控件的值。
现在,再次运行这个应用,这次点击“Change Label’s Text” 按钮。当页重新装载时,你将看到用程序改变(按钮的点击事件代码所为)的值丢失了,也就是说,我们没有看到 Label 的文本变成“Label's Text Changed”。而是再次看到 Label 的初始值。这是因为 Label 控件不是继承自 IPostBackDataHandler 接口,于是 ViewState 负责穿越回传期保持它的值。但又因为 ViewState 是 disabled 的, 所以 Label 丢失了点击“Change Label’s Text” 按钮时它被改变的文本。
现在使能 Label 控件的 ViewState 状态,在点击相同的按钮后,你会看到改变了的值(“Label's Text Changed”)。
所以我们断定,继承自 IPostBackDataHandler 接口的控件将保持它们的值,即使它们的 ViewState 状态被关闭,因为它们的值被保存在 HTTP 提交头里。
作者 Vivek Thakur 简介:MVP (ASP.NET),印度德里市。
[原文]
Myth Regarding ViewState in ASP.NET
By Vivek Thakur
Common myth that ViewState holds values for controls such as TextBoxes.
Introduction
Most ASP.NET developers think that the ASP.NET ViewState is responsible for holding the values of controls such as TextBoxes so that they are retained even after postback. But this is not the case.
I'll explain this with an example. You can download the project files from the link above (you can set the Virtual Directory by the name of ViewState) and run the application. Let's start with a web project in C#.
Open a new ASP.NET Web Application, and on the WebForm, place the following controls accordingly:
Place a web server TextBox control, an HTML server text box control (normal HTML input box with runat=server), a normal HTML input control, and a web server Label control. Name the four controls as:
txtWebServerTest
txtHtmlServerTest
txtHtmlTest
lblTest
Set the Text/Value property to “Initial Text” for the above three TextBoxes, and set the Text property of the Label control to “Initial Label Value”.
Set the EnableViewState property to false for the first and the last controls.
Beneath these controls, place two Button controls and set their text as “Change Label’s Text” and “Postback to Server”. On the button click event handler of the first button, write the following code:
private void btnChangeLabel_Click(object sender, System.EventArgs e)
{
lblTest.Text = "Label's Text Changed";
}
There is no code on the second button’s Click event. It just submits the page to the server.
Now run this application. You can see the initial texts in the controls as you have set.
Now, change the text in all TextBoxes and set them to “Changed Text”. Now click the Post to Server button. What happens is that the first two textboxes retain their values, in spite of the ViewState property being set to false. But the last textbox, which is a simple HTML input control, loses the modified value when the page is reloaded.
Most developers would have expected all three textbox controls to lose their modified values (“Changed Text”), and after page re-loading, they expect “Initial Value” being written on all textboxes as we had disabled the ViewState.
The reason for this behavior is that ViewState is not responsible for storing the modified values for controls such as TextBoxes, dropdowns, CheckBoxList etc., i.e., those controls which inherit from the IPostBackDataHandler interface. After Page_Init(), there is an event known as LoadViewState, in which the Page class loads values from the hidden __VIEWSTATE from the field for those controls (e.g., Label) whose ViewState is enabled. Then the LoadPostBackData event fires, in which the Page class loads the values of those controls which inherit from the IPostBackDataHandler interface, (e.g., TextBox) from the HTTP POST headers.
Now, start the application again, and this time, click the “Change Label’s Text” button. When the page reloads, you will see that the programmatic change (made by our code in the event handler of the button’s Click event) was lost, i.e., we don’t see the Label’s text changed to “Label's Text Changed”. Instead, we see the initial value of the Label again. This is because the Label control does not inherit from the IPostBackDataHandler interface. So the ViewState is responsible for persisting its value across postbacks, and since it has been disabled, the Label loses its value after clicking the “Change Label’s Text” button.
Now enable the ViewState for the Label control, and you can see the modified value (“Label's Text Changed”) after clicking the same button.
So we conclude that controls which inherit from the IPostBackDataHandler interface will retain their values even if the ViewState has been disabled, as their values are stored in HTTP POST headers.
About Vivek Thakur
Vivek Thakur is MVP (ASP.NET) and currently working in a self funded firm as Technology Head in Delhi, INDIA. Vivek graduated with B.Tech from Indian Institute of Technology (IIT), Delhi. Though his expertise lies in Microsoft .NET platform, he is comfortable in J2EE platform besides C/C++, Prolog and MPI-CH. He has deep interest in programming, Chaos Theory and artificial intelligence. Besides his love for software architecture and design, Vivek also focuses on project management skills and has good experience of managing small to medium sized projects. He is also involved in giving training sessions and tutoring.
He is a strong advocate of Chaos Theory in software systems and management.
Vivek also loves music and is the lead guitar player in his band: TechTonica. He loves song writing and music composition, besides listening to different genres of music.
To know more about him one can visit his personal website at: http://www.vivekthakur.com/.