Taking a Bite Out of ASP.NET ViewState

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.
    • 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.
    • 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"))
[C#]
// 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.


<script runat="server"> ' SortField property is tracked in ViewState Property SortField() As String Get Dim o As Object = ViewState("SortField") If o Is Nothing Then Return String.Empty End If Return CStr(o) End Get Set(Value As String) If Value = SortField Then ' same as current sort file, toggle sort direction SortAscending = Not SortAscending End If ViewState("SortField") = Value End Set End Property ' SortAscending property is tracked in ViewState Property SortAscending() As Boolean Get Dim o As Object = ViewState("SortAscending") If o Is Nothing Then Return True End If Return CBool(o) End Get Set(Value As Boolean) ViewState("SortAscending") = Value End Set End Property Private Sub Page_Load(sender As Object, e As EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then BindGrid() End If End Sub Sub BindGrid() ' Get data Dim ds As New DataSet() ds.ReadXml(Server.MapPath("TestData.xml")) Dim dv As New DataView(ds.Tables(0)) ' Apply sort filter and direction dv.Sort = SortField If Not SortAscending Then dv.Sort += " DESC" End If ' Bind grid DataGrid1.DataSource = dv DataGrid1.DataBind() End Sub Private Sub SortGrid(sender As Object, e As DataGridSortCommandEventArgs) DataGrid1.CurrentPageIndex = 0 SortField = e.SortExpression BindGrid() End Sub </script>
[C#]
<%@ 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.


<script runat="server"> // SortField property is tracked in ViewState string SortField { get { object o = ViewState["SortField"]; if (o == null) { return String.Empty; } return (string)o; } set { if (value == SortField) { // same as current sort file, toggle sort direction SortAscending = !SortAscending; } ViewState["SortField"] = value; } } // SortAscending property is tracked in ViewState bool SortAscending { get { object o = ViewState["SortAscending"]; if (o == null) { return true; } return (bool)o; } set { ViewState["SortAscending"] = value; } } void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { BindGrid(); } } void BindGrid() { // get data DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("TestData.xml")); DataView dv = new DataView(ds.Tables[0]); // Apply sort filter and direction dv.Sort = SortField; if (!SortAscending) { dv.Sort += " DESC"; } // Bind grid DataGrid1.DataSource = dv; DataGrid1.DataBind(); } void SortGrid(object sender, DataGridSortCommandEventArgs e) { DataGrid1.CurrentPageIndex = 0; SortField = e.SortExpression; BindGrid(); } </script>

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

 
 

 
 
  
  
  
   
   0736
  
  
  
  
   
   New Moon Books
  
  
  
  
   
   Boston
  
  
  
  
   
   MA
  
  
  
  
   
   USA
  
  
  
  
0877 Binnet & Hardley Washington DC USA
1389 Algodata Infosystems Berkeley CA USA
1622 Five Lakes Publishing Chicago IL USA
1756 Ramona Publishers Dallas TX USA
9901 GGG&G München Germany
9952 Scootney Books New York NY USA
9999 Lucerne Publishing Paris France

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 StateViewState
Holds server resources?YesNo
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:

PagesControls
  • 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" %>

    
        
 
 
<script runat="server"> Private Sub Page_Load(sender As Object, e As EventArgs) Dim ds as New DataSet() ds.ReadXml(Server.MapPath("TestData.xml")) DataGrid1.DataSource = ds DataGrid1.DataBind() End Sub </script>

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

<script runat="server"> Private Sub Page_Load(sender As Object, e As EventArgs) Dim ds as New DataSet() ds.ReadXml(Server.MapPath("TestData.xml")) DataGrid1.DataSource = ds DataGrid1.DataBind() End Sub </script>
[C#]
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data" %>

    
        
    
    
        
 
 

Reducing Page "HTML Payload" by Disabling ViewState

<script runat="server"> void Page_Load(object sender, EventArgs e) { DataSet ds = new DataSet(); ds.ReadXml(Server.MapPath("TestData.xml")); DataGrid1.DataSource = ds; DataGrid1.DataBind(); } </script>

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.

Tamper-Proofing

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:

 
 

Encryption

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:

 
 
  
   validationKey=" 
F3690E7A3143C185AB1089616A8B4D81FD55DD7A69EEAA3B32A6AE813ECEECD28DEA66A
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

<script runat="server"> void GenerateKey(object sender, System.EventArgs e) { int keylength = Int32.Parse(RadioButtonList1.SelectedItem.Value); // Put user code to initialize the page here byte[] buff = new Byte[keylength/2]; RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider(); // The array is now filled with cryptographically strong random bytes rng.GetBytes(buff); StringBuilder sb = new StringBuilder(keylength); int i; for (i = 0; i < buff.Length; i++) { sb.Append(String.Format("{0:X2}",buff[i])); } // paste to the textbox to the user can copy it out TextBox1.Text = sb.ToString(); } </script>

Summary

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
提供的源码资源涵盖了安卓应用、小程序、Python应用和Java应用等多个领域,每个领域都包含了丰富的实例和项目。这些源码都是基于各自平台的最新技术和标准编写,确保了在对应环境下能够无缝运行。同时,源码中配备了详细的注释和文档,帮助用户快速理解代码结构和实现逻辑。 适用人群: 这些源码资源特别适合大学生群体。无论你是计算机相关专业的学生,还是对其他领域编程感兴趣的学生,这些资源都能为你提供宝贵的学习和实践机会。通过学习和运行这些源码,你可以掌握各平台开发的基础知识,提升编程能力和项目实战经验。 使用场景及目标: 在学习阶段,你可以利用这些源码资源进行课程实践、课外项目或毕业设计。通过分析和运行源码,你将深入了解各平台开发的技术细节和最佳实践,逐步培养起自己的项目开发和问题解决能力。此外,在求职或创业过程中,具备跨平台开发能力的大学生将更具竞争力。 其他说明: 为了确保源码资源的可运行性和易用性,特别注意了以下几点:首先,每份源码都提供了详细的运行环境和依赖说明,确保用户能够轻松搭建起开发环境;其次,源码中的注释和文档都非常完善,方便用户快速上手和理解代码;最后,我会定期更新这些源码资源,以适应各平台技术的最新发展和市场需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值