Taking a Bite Out of ASP.NET ViewStateasp.net ViewState brief introduction
Susan Warrenmicrosoft 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 would not 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, Butfirst, Let's Answer That Questions 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 TRAC
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 , AUTOTINATING Both A Lot of Grunt Work and a Lot of Code for Forms. But That Not ViewState.
ViewState is the mechanism ASP.NET uses to keep track of server control state values that do not 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 .
There is Three Small, But Useful Things to Know About ViewState.
You Must Have A Server-Side Form Tag
Getting more from viewstate
ViewState is a marvelous way to track the state of a control across postbacks since it does not use server resources, does not time out, and works with any browser. If you are a control author, you'll definitely want to check out MAINTAING 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 are not 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 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 Sort ORDER
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.
'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 subject (sender as object, e as eventargs) Handles mybase.loadif 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 DataGridsortCommandeventAndArgs)
DataGrid1.currentPageIndex = 0
Sortfield = E.Sortexpression
Bindgrid ()
End Sub
script>
[C #]
<% @ Page language = "c #"%>
<% @ Import namespace = "system.data"%>
// 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 directiondv.sort = sortfield;
IF (! sortascending) {
Dv.Sort = "DESC";
}
// Bind Grid
DataGrid1.datasource = DV;
DataGrid1.databind ();
}
Void Sortgrid (Object Sender, DataGridSortCommandeventEventArgs E) {
DataGrid1.currentpageIndex = 0;
Sortfield = E.Sortexpression;
Bindgrid ();
}
script>
Here's The Code for TestData.xml, Reference 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 vie ?? WState, but are slower and generate a very large ViewState footprint.Session StateViewStateHolds 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 TypeConvertersIncreases "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 do not 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-the you're basicly paying the conversion price twice.getting length 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 us, especially where the viewstate size is signific.
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 the isy 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 does not post back to itself.
Figure 3. Simple Page LessViewState.aspx with DataGrid1
<% @ Import namespace = "system.data"%>
Private subject (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 DRAMATILY 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
Private subject (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"%>
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 do not add security to ViewState if you do not 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 enableViewStateMacAc = 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 do not match, the ViewState data will be discarded And The Controls Will Revert to Their Original Settings.
By Default, ASP.NET Generetes The ViewState Hashcode Using The Sha1 Algorithm. Alternatively, You CAN SELECT The MD5 Algorithm by Setting
In The Machine.config File As Fileows:
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 = "
F3690E7A3143C185AB1089616A8B4D81FD55DD7A69EEAA3B32A6AE813ECEECD28DEA66AE813ECEECD28DEA66A23BEE42193729BD48595EBAFE2C2E765BE77E006330BC3B1392D7C73F "/>
The system.security.cryptography namespace Includes the RNGCRYPTOSERVICEPROVIDER CLASS That You can use to generate this string, as demonstrate in the folload generatecryptoKey.aspx sample:
<% @ Page language = "c #"%>
<% @ Import namespace = "system.security.cryptography"%>
Void GenerateKey (Object Sender, System.EventArgs E)
{
INT keylength = int32.Pars (radiobuttonlist1.selectedItem.value);
// put user code to initialize the page
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 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 form You Won't always need it, but when you do, i think a satisfying addition to the feast of new features asp.net offers to point westurers.