Taking a Bite Out of ASP.NET ViewState

原创 2004年06月15日 15:36:00

Taking a Bite Out of ASP.NET ViewState
ASP.NET ViewState 简要介绍

Susan Warren
Microsoft Corporation

November 27, 2001

When I meet and talk to new ASP.NET page developers, one of the first things they usually ask me is, "What is that ViewState thing, anyway?" And often you can hear in their voices that same queasy fascination I feel when a waiter in some exotic restaurant parks a plateful of some previously unknown food in front of me. Somebody must think it's good; otherwise, they wouldn't be serving it. So, I'll try it, and maybe even love it, but it sure looks odd!

It's that way with ViewState too. Once you get past how it looks, you'll find many circumstances where you'll be delighted to have ViewState in your ASP.NET application, because it lets you do much more with much less code. But there will also be times when you'll want to definitely leave ViewState on the plate. We'll look at both scenarios, but first, let's answer that question about what is ViewState.

Answer: ViewState Maintains the UI State of a Page

The Web is stateless, and so are ASP.NET Pages. They are instantiated, executed, rendered, and disposed on every round trip to the server. As a Web developer, you can add statefulness using well-known techniques like storing state on the server in Session state or by posting a page back to itself. Take the sign up form in Figure 1 as an example.

Figure 1. Restoring posted form values

You can see I've picked an invalid value for my potluck item. Like most forms on the Web, this one is friendly enough to put a helpful error message and a star next to the field in error. In addition, all of the valid values I entered in the other text boxes and drop-down lists still appear in the form. This is possible, in part, because HTML form elements post their current values from the browser to the server in the HTTP header. You can use ASP.NET tracing to see the form values that are posted back, as in Figure 2.

Figure 2. Values posted in HTTP Form, as shown by ASP.NET trace

Before ASP.NET, restoring the values back into the form fields across multiple postbacks was entirely the responsibility of the page developer, who had to pick them out, one-by-one, from the HTTP form, and push them back into the fields. Happily, ASP.NET does this trick automatically, thus eliminating both a lot of grunt work and a lot of code for forms. But that's not ViewState.

ViewState is the mechanism ASP.NET uses to keep track of server control state values that don't otherwise post back as part of the HTTP form. For example, the text shown by a Label control is saved in ViewState by default. As a developer, you can bind data or programmatically set the Label just once when the page first loads, and on subsequent postbacks, the label text will be repopulated automatically from ViewState. So in addition to less grunt work and less code, the benefit of ViewState is often fewer trips to the database.

How ViewState Works

There's really nothing magical about ViewState. It's a hidden form field managed by the ASP.NET page framework. When ASP.NET executes a page, the ViewState values from the page and all of the controls are collected and formatted into a single encoded string, and then assigned to the value attribute of the hidden form field (specifically, ). Since the hidden form field is part of the page sent to the client, the ViewState value is temporarily stored in the client's browser. If the client chooses to post the page back to the server, the ViewState string is posted back too. You can actually see the ViewState form field and its postback value in Figure 2 above.

Upon postback, the ASP.NET page framework parses the ViewState string and populates the ViewState properties for the page and each of the controls. The controls, in turn, use the ViewState data to rehydrate themselves to their former state.

There are three more small, but useful things to know about ViewState.

  1. You must have a server-side form tag (
    ) in your ASPX page if you want to use ViewState. A form field is required so the hidden field that contains the ViewState information can post back to the server. And, it must be a server-side form so the ASP.NET page framework can add the hidden field when the page is executed on the server.
  2. The page itself saves 20 or so bytes of information into ViewState, which it uses to distribute PostBack data and ViewState values to the correct controls upon postback. So, even if ViewState is disabled for the page or application, you may see a few remaining bytes in ViewState.
  3. In cases where the page does not post back, you can eliminate ViewState from a page by omitting the server side tag.

Getting More from ViewState

ViewState is a marvelous way to track the state of a control across postbacks since it doesn't use server resources, doesn't time out, and works with any browser. If you are a control author, you'll definitely want to check out Maintaining State in a Control.

Page authors can also benefit from ViewState in much the same way. Occasionally your pages will contain UI state values that aren't stored by a control. You can track values in ViewState using a programming syntax is similar to that for Session and Cache:

[Visual Basic]

' save in ViewState 
ViewState("SortOrder") = "DESC"

' read from ViewState 
Dim SortOrder As String = CStr(ViewState("SortOrder"))


// save in ViewState 
ViewState["SortOrder"] = "DESC";

// read from ViewState 
string sortOrder = (string)ViewState["SortOrder"];

Consider this example: you want to display a list of items in a Web page, and each user wants to sort the list differently. The list of items is static, so the pages can each bind to the same cached set of data, but the sort order is a small bit of user-specific UI state. ViewState is a great place to store this type of value. Here's the code:

[Visual Basic]

<%@ Import Namespace="System.Data" %>


Storing Non-Control State in ViewState

This example stores the current sort order for a static list of data in ViewState.
Click the link in the column header to sort the data by that field.
Click the link a second time to reverse the sort direction.


<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>


Storing Non-Control State in ViewState

This example stores the current sort order for a static list of data in ViewState.
Click the link in the column header to sort the data by that field.
Click the link a second time to reverse the sort direction.

Here's the code for testdata.xml, referenced in both code sections above:

  0736New Moon BooksBostonMAUSA
0877Binnet & HardleyWashingtonDCUSA
1389Algodata InfosystemsBerkeleyCAUSA
1622Five Lakes PublishingChicagoILUSA
1756Ramona PublishersDallasTXUSA
9952Scootney BooksNew YorkNYUSA
9999Lucerne PublishingParisFrance

Session State or ViewState?

There are certain cases where holding a state value in ViewState is not the best option. The most commonly used alternative is Session state, which is generally better suited for:

  • Large amounts of data. Since ViewState increases the size of both the page sent to the browser (the HTML payload) and the size of form posted back, it's a poor choice for storing large amounts of data.
  • Secure data that is not already displayed in the UI. While the ViewState data is encoded and may optionally be encrypted, your data is most secure if it is never sent to the client. So, Session state is a more secure option. (Storing the data in the database is even more secure due to the additional database credentials. You can add SSL for even better link security.) But if you've displayed the private data in the UI, presumably you're already comfortable with the security of the link itself. In this case, it is no less secure to put the same value into ViewState as well.
  • Objects not readily serialized into ViewState, for example, DataSet. The ViewState serializer is optimized for a small set of common object types, listed below. Other types that are serializable may be persisted in ViewState, but are slower and generate a very large ViewState footprint.
  Session State ViewState
Holds server resources? Yes No
Times out? Yes – after 20 minutes (default) No
Stores any .NET type? Yes No, limited support for: strings, integers, Booleans, arrays, ArrayList, hashtable, custom TypeConverters
Increases "HTML payload"? No Yes

Getting the Best Performance with ViewState

Each object must be serialized going into ViewState and then deserialized upon post back, so the performance cost of using ViewState is definitely not free. However, there's usually no significant performance impact if you follow some simple guidelines to keep your ViewState costs under control.

  • Disable ViewState when you don't need it. The next section, Getting Less from ViewState, covers this in detail.
  • Use the optimized ViewState serializers. The types listed above have special serializers that are very fast and optimized to produce a small ViewState footprint. When you want to serialize a type not listed above, you can greatly improve its performance by creating a custom TypeConverter for it.
  • Use the fewest number of objects, and if possible, reduce the number of objects you put into ViewState. For example, rather than a two-dimensional string array of names/values (which has as many objects as the length of the array), use two string arrays (only two objects). However, there is usually no performance benefit to convert between two known types before storing them in ViewState—then you're basically paying the conversion price twice.

Getting Less from ViewState

ViewState is enabled by default, and it's up to each control—not the page developer—to decide what gets stored in ViewState. Sometimes, this information is not useful to your application. While it's not harmful either, it can dramatically increase the size of the page sent to the browser. It's a good idea to turn off ViewState if you are not using it, especially where the ViewState size is significant.

You can turn off ViewState on a per-control, per-page, or even per-application basis. You don't need ViewState if:

Pages Controls
  • The page doesn't post back to itself.
  • You aren't handling the control's events.
  • The control has no dynamic or data bound property values (or they are set in code on every request).

The DataGrid control is a particularly heavy user of ViewState. By default, all of the data displayed in the grid is also stored in ViewState, and that's a wonderful thing when an expensive operation (like a complex search) is required to fetch the data. However, this behavior also makes DataGrid the prime suspect for unnecessary ViewState.

For example, here's a simple page that meets the criteria above. ViewState is not needed because the page doesn't post back to itself.

Figure 3. Simple page LessViewState.aspx with DataGrid1

<%@ Import Namespace="System.Data" %>


With ViewState enabled, this little grid contributes over 3000 bytes to the HTML payload for the page! You can see this using ASP.NET Tracing, or by viewing the source of the page sent to the browser, as shown in the code below.


Yikes! By simply disabling ViewState for the grid, the payload size for the same page becomes dramatically smaller:


Here's the complete LessViewState code in Visual Basic and C#:

[Visual Basic]

<%@ Import Namespace="System.Data" %>


Reducing Page "HTML Payload" by Disabling ViewState


<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>


Reducing Page "HTML Payload" by Disabling ViewState

Disabling ViewState

In the example above, I disabled ViewState for the grid by setting its EnableViewState property to false. ViewState can be disabled for a single control, for an entire page, or for an entire application, as follows:

Per control (on tag)
Per page (in directive) <%@ Page EnableViewState="False" ... %>
Per application (in web.config)

Making ViewState More Secure

Because it's not formatted as clear text, folks sometimes assume that ViewState is encrypted—it's not. Instead, ViewState is merely base64-encoded to ensure that values are not altered during a roundtrip, regardless of the response/request encoding used by the application.

There are two levels of ViewState security you may wish to add to your application:

  • Tamper-proofing
  • Encryption

It's important to note that ViewState security has a direct effect on the time required to process and render an ASP.NET page. In short, more secure is slower, so don't add security to ViewState if you don't need it.


A hashcode will not secure the actual data within the ViewState field, but it will greatly reduce the likelihood of someone tampering with ViewState to try to spoof your application, that is, posting back values that your application would normally prevent a user from inputting.

You can instruct ASP.NET to append a hashcode to the ViewState field by setting the EnableViewStateMAC attribute:

<%@Page EnableViewStateMAC=true %>

EnableViewStateMAC can be set at the page or application level. Upon postback, ASP.NET will generate a hashcode for the ViewState data and compare it to the hashcode store in the posted value. If they don't match, the ViewState data will be discarded and the controls will revert to their original settings.

By default, ASP.NET generates the ViewState hashcode using the SHA1 algorithm. Alternatively, you can select the MD5 algorithm by setting in the machine.config file as follows:


You can use encryption to protect the actual data values within the ViewState field. First, you must set EnableViewStatMAC="true", as above. Then, set the machineKey validation type to 3DES. This instructs ASP.NET to encrypt the ViewState value using the Triple DES symmetric encryption algorithm.

ViewState Security on a Web Farm

By default, ASP.NET creates a random validation key and stores it in each server's Local Security Authority (LSA). In order to validate a ViewState field created on another server, the validationKey for both servers must be set to the same value. If you secure ViewState by any of the means listed above for an application running in a Web Farm configuration, you will need to provide a single, shared validation key for all of the servers.

The validation key is a string of 20 to 64 random, cryptographically-strong bytes, represented as 40 to 128 hexadecimal characters. Longer is more secure, so a 128-character key is recommended for machines that support it. For example:

23BEE42193729BD48595EBAFE2C2E765BE77E006330BC3B1392D7C73F" />

The System.Security.Cryptography namespace includes the RNGCryptoServiceProvider class that you can use to generate this string, as demonstrated in the following GenerateCryptoKey.aspx sample:

<%@ Page Language="c#" %>
<%@ Import Namespace="System.Security.Cryptography" %>


Generate Random Crypto Key

40-byte 128-byte  

Copy and paste generated results


ASP.NET ViewState is a new kind of state service that developers can use to track UI state on a per-user basis. There's nothing magical about it. It simply takes an old Web programming trick—roundtripping state in a hidden form field—and bakes it right into the page-processing framework. But the result is pretty wonderful—a lot less code to write and maintain in your Web-based forms.

You won't always need it, but when you do, I think you'll find ViewState is a satisfying addition to the feast of new features ASP.NET offers to page developers.

Susan Warren is a program manager for ASP.NET on the .NET Framework team.


  • wangyajin333
  • wangyajin333
  • 2014年02月19日 14:11
  • 1214

关于机房交换机故障导致HDFS NameNode挂掉的问题

HDFS HA中,一个active NN,一个standby NN,三个JNs,共涉及三台机器146.66/67/68。其中66上有一个JN,67上一个JN和一个active NN,68上一个JN和一...
  • sdn_prc
  • sdn_prc
  • 2015年11月13日 16:57
  • 1337

探索Asp.net mvc 的文件上传(由浅入深)

原文链接 代码下载:http://files.cnblogs.com/n-pei/mvcfileupload.zip 最近因为TeamVideo需要用到视频和图片上传功能,所以试着Google了...
  • chaoyangzhixue
  • chaoyangzhixue
  • 2016年02月17日 19:14
  • 1315


/**     QQ群:223494678     函数:模拟post得到所有分页的页面信息     参数:         string $EVENTARGUMENT         st...
  • Allen_Tsang
  • Allen_Tsang
  • 2015年07月27日 18:35
  • 1154


用.NET做的网站如果做成POST提交方式,且开了viewstate的话,采集起来有点小繁琐,在此跟大家分享一下做法。 采的难点是必須先取得表單裏面的viewstate和datavalidtion兩...
  • sibang
  • sibang
  • 2014年08月21日 16:56
  • 545

ASP.NET 状态管理(视图状态 ViewState)

无论 Web 程序框架多么先进,它都不能改变一个事实:HTTP是一种无状态协议。        每次 Web 请求后,客户端和服务器端断开,同时 ASP.NET 引擎释放页面对象。这种架构保证了...
  • my98800
  • my98800
  • 2016年04月29日 12:58
  • 149


ASP.NET状态管理之十一(视图状态ViewState) 视图状态是 ASP.NET 页框架默认情况下用于保存往返过程之间的页和控件值的方法。当呈现页的 HTML 形式时,需要在回发过程中...
  • yaofayong
  • yaofayong
  • 2012年05月12日 22:09
  • 194


在ASP.NET中,有很多种保存信息的对象。例如:Application,Session,Cookie,ViewState和Cache等,那么它们有什么区别呢?每一种对象应用的环境是什么? 为了更清...
  • yangchun1213
  • yangchun1213
  • 2012年03月15日 22:54
  • 501

ASP.NET ViewState 详解

概述 ViewState是一个被误解很深的动物了。我希望通过此文章来澄清人们对ViewState的一些错误认识。为了达到这个目的,我决定从头到尾详细的描述一下整个ViewState的工作机制,其中我...
  • landy_john
  • landy_john
  • 2012年05月18日 16:24
  • 667


  • u013598542
  • u013598542
  • 2015年04月09日 20:36
  • 656
您举报文章:Taking a Bite Out of ASP.NET ViewState