`
txf2004
  • 浏览: 6978145 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

对 ASP.NET 中 ViewState 对象的荒谬认识

阅读更多

--普遍荒谬的认为 ViewState 对象保持着控件例如 TextBox 的值。

大多数 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),印度德里市。
翻译: 张庆 (http://www.why100000.com) 2007.5.17

[原文]
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.

分享到:
评论

相关推荐

    .net 中viewstate的原理和使用

    2. 用户进行某些操作后(例如更改表单中的数据),这些更改会被编码成一系列键值对,并存储在ViewState对象中。 3. 页面返回到客户端时,ViewState作为隐藏字段嵌入到HTML源码中,一同发送给客户端浏览器。 4. 当...

    ASP.NET ViewState 初探

    ASP.NET ViewState 是一种机制,主要用于在Web应用的页面往返行程中保持用户界面(UI)的状态。由于Web的本质是无状态的,每次用户请求页面时,服务器都会创建一个新的页面实例,而ASP.NET页面也不例外。这就意味着...

    理解ASP.NET的ViewState

    ASP.NET页面遵循一个预定的事件序列,在这个过程中,ViewState扮演着关键角色。当用户请求一个ASP.NET页面时,服务器会执行一系列事件处理程序来构建并渲染页面。这些事件包括初始化、加载状态、预渲染等。ViewState...

    ASP.net压缩ViewState,ASP.net操作EXCEL,Word,ASP.net获得验证码,汉字验证码、扭曲验证码

    为了优化性能,ASP.NET允许我们对ViewState进行压缩,减少在网络上传输的数据量。可以通过实现IStateFormatter接口或使用第三方库如GZipStateFormatter来实现这个功能。 接下来,我们讨论ASP.NET操作Excel和Word的...

    asp.net页面中的viewstate内容解析器

    在ASP.NET中,ViewState是一种关键机制,用于在页面之间持久化控件的状态。当用户与网页交互时,比如填写表单或点击按钮,ViewState会存储这些交互信息,以便在后续的HTTP请求中恢复这些状态。 ViewState的内容是...

    asp.net保存信息对象比较

    在 ASP.NET 中,有几种主要的对象用于保存信息,包括 Application、Session、Cookie、ViewState 和 Cache。这些对象各有其特点,适用于不同的场景。 1. **Application 对象** Application 对象用于存储所有用户...

    比较ASP.net中的Session、ViewState、Application、Cookies

    比较学习ASP.net中的Session、ViewState、Application、Cookies

    ASP.NET01页面对象模型

    ASP.NET页面对象模型是微软开发的ASP.NET框架中的核心概念,用于处理Web应用程序中的用户交互、数据处理和页面生命周期管理。这一模型为开发者提供了一种结构化的编程方式,使得创建动态网页变得更加高效和灵活。 ...

    asp.net中ViewState的用法详解

    ***中的ViewState是.NET Framework提供的用于在Web表单页面和服务器之间的往返(Postback)过程中保持页面控件状态的一种机制。下面详细介绍ViewState的原理、用法、与Session的对比以及使用ViewState时需要注意的...

    asp.net 2.0中通过压缩ViewState

    在ASP.NET 2.0中,ViewState是一个关键特性,用于在客户端和服务器之间保持页面状态。然而,随着页面复杂性的增加,ViewState可能会变得非常大,导致页面载入速度变慢,尤其是对于使用AJAX(异步JavaScript和XML)...

    ASP.NET资料ASP.NET资料

    这个压缩包中的“ASP.NET资料”很可能包含了关于ASP.NET的各种学习资源,如教程、示例代码、文档等,对于学习和掌握ASP.NET技术具有极大的帮助。 ASP.NET的核心特性包括: 1. **页面生命周期管理**:ASP.NET提供了...

    ASP.NET PAGE对象使用

    ASP.NET PAGE对象使用了解ASP.NET 页的结构 掌握Page对象的各种事件和属性 理解_ViewState 对象 理解代码隐藏的概念

    asp.net相关资料,asp.net内建对象,ASP和asp.net,ServerVariablesd的环境变量

    本文将深入探讨ASP.NET内建对象、ASP与ASP.NET的区别以及ServerVariables中的环境变量,旨在帮助读者全面理解这个强大的Web应用程序框架。 首先,ASP.NET内建对象构成了ASP.NET开发的基础,它们是系统自动提供的,...

    ASP.NET ViewState

    总的来说,ASP.NET ViewState是一个强大的工具,它使得在无状态的Web环境中保持状态成为可能,但也需要谨慎使用和适当优化,以平衡功能性和性能。了解如何有效地管理和调整ViewState是每个ASP.NET开发者必备的技能。

    ASP.NET 程序设计基础篇(VB.net)

    4. **ViewState**:ASP.NET的ViewState机制用于在多个回发之间保持控件的状态。虽然方便,但也会增加页面大小,需要合理管理。 5. **Master Pages和Themes**:Master Pages用于创建统一的页面布局,而Themes则可以...

    ASP.NET_Application,Session,Cookie和ViewState等对象用法和区别

    在 ASP.NET 中,Application、Session、Cookie 和 ViewState 是四种常见的对象,每种都有其特定的用途和特点。 1. **Application 对象** Application 对象用于在整个应用程序生命周期内共享数据,这包括所有用户。...

    asp.net实现的简单留言板

    6. 页面间通信:ASP.NET的ViewState或Session机制可以用来在页面间传递信息,例如保持用户登录状态,或者在显示留言列表时回显用户之前的输入。 7. 错误处理和安全性:为了提供健壮的应用,需要考虑错误处理和安全...

    asp.net服务器端保存viewstate例子,html中不在有viewstate

    ASP.NET中的ViewState是用于在页面回发期间保持控件状态的一种机制。它是一个隐藏的字段,存储在HTML中,包含了页面及其控件的所有状态信息。然而,由于ViewState数据的体积通常较大,它会增加页面的大小,从而影响...

    ASP.NET制作的一个在线计算器

    6. **Response对象**:ASP.NET使用HttpResponse对象来生成并发送响应给客户端。在计算器的事件处理函数中,开发者会使用`Response.Write`方法将计算结果输出到网页上。 7. **AJAX技术**:为了实现无需刷新页面的...

Global site tag (gtag.js) - Google Analytics