ASP.NET State Management: View State

Posted on March 14, 2004   |   Download sample code

90 comments

ASP.NET view state is a great feature and an essential tool for web development of today. It maintains the state of a page as it travels back and forth. There is no more need to worry about restoring values of page controls between postbacks. In this article you will get an in-depth perspective on view state. We will talk about ways of reducing unnecessary payload and protecting view state from prying eyes.

Among IT professionals it has become popular to debunk, dissect, expose, and unleash things. In this article we will first debunk view state, and then dissect it. No, first unleash then debunk. I think.

Dissecting View State

As far as web developers are concerned, the web is stateless. This statement will serve as the cornerstone of our entire discussion of view state. Therefore I’ll say it again—as far as we are concerned, the Web is stateless.

For example, you request an ASP.NET page from a web server. Once the page is processed on the server and returned to you that same server does not remember the page anymore. Even a slight page postback initiates the same request sequence and the web server performs the same task again as if it never saw this page in the first place. This is the grand difference between web applications and their desktop counterparts. On the desktop you can maintain state between requests. On the web it’s a much harder task.

How do you retain text in input boxes, selections of dropdown controls, etc? To maintain state on the web you need help. ASP.NET goes a long way giving you the necessary support to carry on the page state from one request to another, and it does so seamlessly. Sometimes so seamlessly that you may overlook a large chuck of text you drag around. Hold this thought. We'll get back to it shortly.

To summarize view state's mission in once sentence—view state helps you maintain values through subsequent requests of the same (!) page.

Where Is View State Stored?

View state is simply text. It is an aggregate of values of controls on a page. It's a string that contains values of page controls hashed and encoded in some manner. The view state contains no information about the server or the client. It only comprises information about the page itself and its controls. It lives along with the page in the user's browser.

As a rule, view state is stored right in the page and therefore it travels with it back and forth. Remember good old hidden input fields? View state is nothing more than a hidden input which holds a hash of control values. If you view the source of an ASP.NET web form you will see something like this:

<input type="hidden" name="__VIEWSTATE" 
            value="CEbzzzEnmmz+Bc8IDFlnpgCLJ/HB00...>

Nobody in sane mind can read these strings fluently. What you see here is a base64 encoded string. I emphasize encoded because some folks assume view state is encrypted. Base64 is not an encryption algorithm. Base64 makes a string suitable for HTTP transfer plus it makes it a little hard to read. Just a little. It's easy to decode this string and see what's inside. Can this be a security issue? It sure can. We'll address your concern in due time. Stick around.

How Is View State Built?

Every server control ultimately derives from the Control class. Be it a WebControl, HtmlControl or even LiteralControl it has a property called EnableViewState. When a page is built every control that has this property enabled contributes to the view state by serializing its contents (in this case: converting its contents into a string). Now, some controls are easy to serialize, while others might give us grief.

What manages the view state is the StateBag class. This class is like a dictionary—you may store key/value pairs in it. This is how you store a piece of useful data in the view state:

ViewState ["SortOrder"] = "email"

When the page posts back its view state is taken apart (decoded) on the server and each control participating in the view state gets its value restored.

There's an interesting gotcha you need to be aware of. Some controls get their values restored automatically (courtesy of ASP.NET) and you don't need to maintain their values! I put together two almost identical pages—one is an ASP.NET web form, and the other one is plain HTML.

The ASP.NET page has its view state turned off completely. See how it maintains text and selections once you click Submit. Scroll down to "Form Collection" to see what was posted. ASP.NET restored these values automatically!

Form posback values

The second page is old, "traditional", HTML. Click Submit to receive proof that control values won't be restored.

What's the moral of this story? You don't always need view state enabled to maintain page state. "When do I need it though? What's it for then?" Glad you asked. The prime candidates for participation in view state are those controls that don't post back with the HTTP form and controls added or populated dynamically.

Let me give you an example. Suppose you have an empty dropdown list which you populate with user names from the database. When the page runs for the first time (!Page.IsPostback. Rings a bell?) you need to databind it and fill it with user names. What happens once the page loads? Without view state the dropdown list will be empty. As you enable view state the dropdown list content will be restored on postback. Or... you would have to populate the list from the database every time the page posts back! If you weigh database access vs. view state the scale tips in favor of view state (unless the list of users is so huge that you'd rather ping the database each time instead of dragging around a giant view state string).

What Exactly Can I Store in View State?

Documentation states the view state is "optimized" for a small number of types. The lucky ones are strings, integers, booleans, ArrayLists and HashTables. Everything else should either be serializable or have a TypeConverter defined for it.

Beware of performance drawbacks for complex types. Serializing and deserializing a complex object could incur too much overhead. Choose wisely! Consider storing such an object in Session or Cache instead. Remember—whatever you store in the view state travels back and forth wasting bandwidth and making page downloads slower.

Susan Warren has kindly put together this decision chart of view state vs. session:

  Session State View State
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

As you see some objects are a perfect fit for view state, while others had better be stored in the session. If you still need to store an object in the view state think about creating a TypeConverter for it to improve performance.

How Do I Enable View State?

You may do so on the machine, application, page and control level. First, you must have a server side form (<form runat="server">). By default view state is enabled (as of ASP.NET 1.1). A quick peek into machine.config reveals this much:

<pages enableViewState="true" enableViewStateMac="true" ... />

The nature of machine.config prescribes general settings for all applications. In other words since view state is enabled on the machine level it is enabled on the application, page and control level. Thus each server control has view state enabled by default. Settings roll downhill so to say.

How Do I Disable View State?

Again, you may do so on the machine, application, page and control level. To disable view state of an individual control set its EnableViewState to false:

<asp:Label id=Label1 runat="server" EnableViewState="false" />

As a rule of thumb if a control does not contain any dynamic data, or its value is hardcoded or assigned on every page request and you're not handling its events you can disable the control's view state.

A good example of a big consumer of view state is the DataGrid control. Should you enable its view state or not? It depends. Again, if the page with the DataGrid does not post back you can live without view state just fine. On the other hand, if the DataGrid has sorting or paging enabled you will want view state.

Remember, DataGrid renders as a table with rows and cells being its child controls. View state is maintained for these child controls. The DataGrid has no memory of the datasource you bound it to! The datasource is NOT stored in the viewstate.

You may also disable view state on an entire page by modifying the Page directive:

<%@ Page ... EnableViewState="false" %>

If you really wish you may also disable view state on the whole web application by adding the following line to your web.config:

<pages enableViewState="false" />

When In Page Lifecycle Is It Safe To Use View State?

In the page lifetime cycle view state is available between the Init and PreRender events. If you need to dig deeper into the class behind the view state check out StateBag and StateItem.

Can I Get Rid Of View State Completely?

No. You will always have a relatively short string representing the page itself even if you turn off the view state on each and every control.

Size Matters

Spammers know better. By trimming the view state where you can live without it you do yourself and others a favor by reducing payload and improving page performance. Just recently we were cleaning up dead view state in our main product at work. I was shocked how much lighter most pages have become. A couple of pages that didn't post back had large databound controls. By disabling view state on one of them the size of the view state went from 28K to 20 bytes! Quoting a 1400% reduction would be ridiculous but you get the point. The whole exercise proved to be well worth it. You need to thoroughly understand what each page does before you trim its view state.

Adressing Security Issues

I started my career as a hacker (A note to Big Brother: there's nothing interesting here. Go away). My first languages where Pascal (oh yes, Borland was beating Microsoft back then), Assembler and then C++ (another score for Borland and Zortech). I can tell you right up front—if something can be engineered, it can as well be reverse engineered. Not that all "security consultants" out there suck... Still, Microsoft folks in their infinite wisdom gave us tools to protect our view state or at least make it tamper-resistant. And please remove that PostIt with the admin login off the server case.

The good thing in our story is that the "shared secret" is stored on the server away from prying eyes. Now you can assure your clients that no sensitive information will leak into the wrong hands. At least not via view state. You can put that stickie back now.

Protecting View State: The Easy Way

Once again, view state is represented as a base64-encoded string. The keyword here is encoded. Not encrypted. Therefore if you were to decode it you would be able to gain insight of the workings of a web page. Maybe someone would be smart enough to store a credit card number in view state! This also means that someone may build their own page, pre-fill it and send it to your server (one-click attack) thus fooling it to believe it's dealing with a legitimate page. There's a simple yet effective way to counter this attack.

By default ASP.NET builds a so-called Message Authentication Code (MAC) and appends it to the view state. When the page posts back ASP.NET recalculates the hash and compares it to the one that arrived with the view state string. If they are different it reverts to old control values. If you peek into your machine.config again you'll notice that MAC validation is on by default:

<pages ... enableViewStateMac="true" />

It is strongly recommended that you keep MAC validation enabled at all times. It works well to prevent spoofing attacks, i.e. when an attacker feeds values that you normally don't allow. This validation doesn't work too well with one-click attacks, though, because the view state will appear to be valid and the page will execute under the security context of the user.

To thwart one-click attacks you can resorts to another simple technique. In ASP.NET 1.1 the Page class has a very useful property, ViewStateUserKey. Set it in Page_Init to some unique value (authenticated user ID, for example).

Note: This is not an issue if users browse anonymously and don't participate in sensitive transactions.

By default ASP.NET creates MACs using the SHA1 hashing algorithm:

<machineKey ... validation="SHA1"/>

If you wish you may instruct it to use MD5 instead. SHA1 produces a larger hash than MD5 and is therefore considered more secure. Keep in mind, though, that the view state string can still be base64-decoded and viewed on the client.

Protecting View State: The Hard Way

It's not really that hard. You can go beyond comparing view state hashes and have it encrypted as well. This is a two step process:

  1. Set enableViewState="true"
  2. Set machineKey validation type to 3DES. This causes ASP.NET to encrypt the view state.

Your web.config should have these two entries:

<pages enableViewState="true" enableViewStateMac="true" />
<machineKey ... validation="3DES" />

Simple as that. Here's what happens behind the covers: ASP.NET creates a random encryption key and stores it in each server's Local Security Authority (LSA). Therefore it becomes virtually impossible to decrypt the view state string since the "shared secret" is stored on the server. ASP.NET uses the key from LSA to encrypt and decrypt the view state.

Protecting View State: Web Farm Scenario

By default ASP.NET uses autogenerated keys for view state validation and encryption. Validation and decryption happen separately and therefore two different keys are employed. Both keys reside in each server's SLA. What happens if your web application runs in a web farm? How would you facilitate a view state that came from another server? Obviously the set of keys from this other server will be different (remember, they are generated automatically and therefore are unique?).

The way out is to create both the validation and decryption keys by hand and store them in your web.config:

<machineKey
      validationKey="value,[IsolateApps]" 
      decryptionKey="value,[IsolateApps]" 
      validation="SHA1|MD5|3DES" />

Let's take a closer look at machineKey attributes:

  • validationKey specifies the key for validation of the view state. ASP.NET will use this key when calculating MACs. The key must be 20 to 64 bytes (40 to 128 hexadecimal characters). The recommended key length is 64 bytes. This key should be generated in a random manner. If you tag IsolateApps to the end of the key value ASP.NET will generate a unique key for each application using the application's ID.
  • decryptionKey specifies the key used to encrypt and decrypt the view state when validation="3DES". They key must be 8 for DES encryption or 24 bytes for 3DES (16 or 48 hexadecimal characters respectively). The recommended key length is 48 bytes. This key should be generated in a random manner. If you tag IsolateApps to the end of the key value ASP.NET will generate a unique key for each application using the application's ID.
  • validation sets the type of encryption. When set to SHA1 or MD5 it instructs ASP.NET to use either SHA1 or MD5 algorithm to create view state MACs. When set to 3DES instructs ASP.NET to encrypt the view state (also provides integrity checking) with the help of the Triple-DES symmetric encryption algorithm.

For your convenience I've put together an online machineKey Generator. The tool creates a complete machineKey that you can paste in your web.config.

If you still have doubts that view state can be very secure read on—you'll learn how to store it in the database.

Keeping View State On The Server

The good old Page class allows us to tap into the process of storing and loading view state. With the technique you can reroute the view state to a database. Why would you want to? Maybe you manipulate a lot of dynamic data and your view state is till big aggravating matters for users with slow internet connections. Or maybe you are still concerned that someone decrypts the view state in spite of all these tight security measures. You are free to use this technique. After all, the page is only the view state's default persistence media.

The Page class gives us the right tools for the job. It provides two handy virtual methods:

protected virtual 
      void SavePageStateToPersistenceMedium(object viewState);

protected virtual 
      object LoadPageStateFromPersistenceMedium();

You can easily guess from their names that these two methods persist view state to and load from a medium. This medium can be just about anything—a file, a database, etc.

At the beginning of this article I explained the role of the StateBag class. I also said that the view state is represented as a textual string. How does the conversion happen? There's hope. It lies with the class called LosFormatter.

These days MSDN states that LosFormatter

"serializes the view state for a Web Forms page" and "is designed for highly compact ASCII format serialization. This class supports serializing any object graph, but is optimized for those containing strings, arrays, and hashtables. It offers second order optimization for many of the .NET primitive types."

Good enough. LosFromatter lists two methods we're after:

public void Serialize(Stream, object);
public void Serialize(TextWriter, object);

and

public object Deserialize(Stream);
public object Deserialize(string);
public object Deserialize(TextReader);

The Serialize method is the one that converts an instance of StateBag (second parameter) and writes it into a Stream or TextWriter. The Deserialize method performs the opposite task. It builds an instance of StateBag from a base64 encoded string, a stream or a TextReader.

Some code is in order to illustrate the mechanics of view state persistence:

protected override 
    SavePageStateToPersistenceMedium (object ViewState)
{
  StringBuilder sb = new StringBuilder ();
  StringWriter swr = new StringWriter (sb); 

  LosFormatter formatter = new LosFormatter ();
  formatter.Serialize (swr, viewState);
  swr.Close ();

 // Store the textual representation of ViewState in the 
 // database or elsewhere
 // The serialized view state is available via sb.ToString ()
}

protected override object LoadPageStateFromPersistenceMedium()
{
  object objViewState;
  string strViewState;

  // Viewstate should be read from the database or  
  // elsewhere into strViewState
  LosFormatter formatter = new LosFormatter ();
  try
  {
    objViewState = formatter.Deserialize (strViewState);
  }
  catch
  {
    throw new HttpException ("Invalid viewstate");
  }
  return objViewState;
}

Feel free to download a full-fledged sample of this code.

Burning View State Fat

Reflecting on our experience of our flagship product at work, I'd like to share a little "success story". We decided to give the code above a try and redirected view state persistence to the database. Next we ran stress tests in Microsoft Application Center Test (ACT) which comes for free with Visual Studio.NET. Preliminary results were surprising. Even though database access is slower than simply retrieving view state from the hidden __VIEWSTATE field, when the view state is large enough—and it is since our application manipulates a lot of dynamic data—the reduction in page download and postback time outweighted storing the view state to and retrieving from the database! In other words, by serving leaner pages we were able to process more requests within the same time span of a stress test cycle and save bandwith while persisting view state in the database.

"View State Is Invalid" Error Message When You Use Server.Transfer

Actually, this is exactly how KB316920 is titled. This KB article deals with an issue I've seen come up in newsgroups quite often.

Here's the gist of the problem. Suppose you have a web page. The first page has a MAC appended to its view state (which is done by default, remember?). Now, what if you need to call Server.Transfer and you want to preserve its QueryString and the Form collection? You may do so by calling an overloaded Server.Transfer and passing true as its second parameter.

Next, when this second page is invoked it receives the view state of the calling web form in its __VIEWSTATE hidden field. The view state authentication check will fail since the newly arrived view state is invalid on the second page.

The KB article makes its point clear—view state is page scoped and is valid for that page only. View state should not be transferred across pages.

Summary

View state is of tremendous value for web developers. It abstracts you from the dirty work of persisting and restoring control values between page postbacks. However its ease of use has a price tag on it and you need to clearly understand when you do need to maintain view state at the expense of serving larger pages, and when you don't at the expense of inability to facilitate dynamic data. Decide judiciously what to store in the view state to avoid incurring overhead. This article taught you how to secure the view state from tampering. You also learned how to take it out of web forms and persist it on the server.

90 comments

John Spurlin
on April 08, 2004

This is the best article on viewstate I have read. It is concise and thorough.


andy
on May 22, 2004

I've been searching for weeks for a document like this. well done. thanks!


Robert Pegg
on June 09, 2004

Thanks! I have been working in a farm environment and lately have run into some viewstate issues. Although I understood viewstate (or thought I did), I needed a lttle more depth in an easy to read and comprehend format. I appreciate you taking the time to write this down.


Niranjan Srinivasan
on August 17, 2004

Very lucid explanation. Keep up the great work.


Don Almeida
on September 30, 2004

Is there a size limitaiton on ViewState?


Milan Negovan
on September 30, 2004

I don't think there's a limitation.


Bids
on October 01, 2004

Its a great article on View state.


Damien McGivern
on November 29, 2004

I've always been wary of view state; now I'm scared of it! Great article.


Lars Kjeldsen
on January 05, 2005

Best article I have ever read on viewstate - really good work. Thanks for putting in the effort.


Leon
on January 25, 2005

How to uniquely identify the page's viewstate when keeping in server if the page is access by multiple user or same user multiple browser.


Milan Negovan
on January 25, 2005

When several users access a page at the same time each one gets its own Session ID, so it's easy to tell which view state goes with which user session.

When a user opens a page in several windows/tabs of their browser, the session ID will stay the same. You need to hit this page at the exact same split second to create a conflict. Whether a conflict occurs at all will depend on how dynamic that page is, i.e. how much its view state changes. Personally, I wouldn't worry about it. It's a possible, yet unrealistic scenario.


Morgan Skinner
on February 28, 2005

I've pointed my customers to this article numerous times, and finally got around to thanking you for it. It's an excellent article, tells you all you need to know about viewstate, and your machine key generator has saved my bacon a couple of times too. Thanks!


Milan Negovan
on February 28, 2005

Glad you've found it helpful, Morgan. ;)


Naveen
on March 17, 2005

Very lucid, very comprehensive, liked it a lot!


bala
on March 17, 2005

Its very helpful.


Rosi Reddy
on March 24, 2005

This is the excellent article. I have ever seen this much good article on view state... Keep it up.....


Sirisha
on April 28, 2005

Can you please help me out .I am facing a problem , I tried number of things and asked my friends but failed to get the solution ,finally decided to ask your suggestion.

I have read a book asp.net server control and components By Nikhil .With it's and with the help of reflector created by Roeder . I have create a user control . It has custom view state . I have a collection with in collection . then the items with in collection has various properties. I am getting the form as required for the first time . but after post back i am not getting the property values, but it is showing the collection count as 4( number of items I added in the collection).
But the property values for the items are null.

Can u please help me with some suggestion where I am going wrong. Your suggestion will help me a lot in solving the problem.
If you say I can even send the code for your better understanding of the problem.Thanking you.

Regards,
Sirisha


Sirisha
on May 06, 2005

Hello ,
The articles is really very infomative . I have recommended to my friends too. I would like to take oppertunity to mail an issues related to View State. [giant code listing deleted]


Milan Negovan
on May 06, 2005

Sirisha, be reasonable. This really isn't a dicussion forum here. Ten page downs of souce code is more suitable for ASP.NET Forums.


Burt
on May 26, 2005

This is the best article on ViewState vs Session that I have seen to date! Keep up the good work.


Mike Ogden
on August 29, 2005

Do you know if it's possible to avoid loading the entire viewstate for a page into memory? I have a data-driven asp.net application and for very large queries the viewstate data grows to MB sizes. I overrode the ViewState methods to load and save the viewstate to a file on the server instead of in the html page, but on a postback I may get OutOfMemory exceptions. I was hoping to replace the loading of viewstate with a streamreader or something like that so the entire viewstate wouldn't have to be loaded into memory. This is killing my application scalability. please help! :)


Milan Negovan
on August 30, 2005

Mike, first and foremost, I'd do my best to figure out why view state is so gigantic. Maybe you're better off caching the datasource and disabling view state on data bound controls. Look at every control and see if it needs to contribute to view state or not.

Other than that I suggest reading Nikhil Kothari's book on server controls. He has plenty of coverage of custom view state management.


Bryan Wang
on September 12, 2005

I run into a problem when I am trying to cut back the unnessary PostBacks, so I change the control state by client-side script (javascript), for example, use js to check the checkboxes in a DataGrid, so how do I capture the changed state on PostBack? In other words, how can I modify the ViewState to reflect the new State at the Client Side?

Thanks,


Milan Negovan
on September 12, 2005

Bryan, you can't change view state from client-side script. You can go ahead and select/deselect checkboxes from js even if you disable view state on them. ASP.NET will restore their state anyway.


JfK
on October 13, 2005

Can I Get Rid Of View State Completely? You said NO, I say YES: what you have to do is:
1. turn off ViewState in normal way (machine.config, web.config, @ directive, whatever)
2. Override two functions in class inheriting from Page: SavePageStateToPersistenceMedium and LoadPageStateFromPersistenceMedium. First one has to be empty, second one returns null.
3. Tadaaa, no ViewState on the page. The only thing which is left is hidden input which ought to contain viewstate.


Milan Negovan
on October 13, 2005

I wouldn't go that far because the page "checksum" is there for a reason.


JfK
on October 27, 2005

Hmm, ok, but what is the reason for this 'checksum' when you don't use viewstate anyway? I mean that when you've turned off viewstate for your app or machine why shouldn't you get rid off this little viewstate scrap that is left behind? If I have some time I'll dive into Framework in hope of exploring what is this 'checksum' reason (I personally think that it is output of GetHashCode of the page, but I'm not sure about it)


Ruchita
on January 31, 2006

This is the best article on viewstate i have read so far....


Orlin
on February 17, 2006

Fantastic article! One of the best articles I have read in my life.


Erik
on March 06, 2006

Milan, you said 'I wouldn't go that far because the page "checksum" is there for a reason.'. I can't find anywhere what the reason exacly is.. do you know more than just that its there 'for a reason'?


Milan Negovan
on March 06, 2006

I'm not 100% sure how the bare-bones checksum is built, but there's really no way of getting rid of it completely.


Kaushal
on April 25, 2006

Really an exceptional article on viewstate. Tons of thanks to Milan Negovan to provide such useful information.


Bruce Hemmerich
on May 26, 2006

I really enjoyed the article. I am going to try the code to save the viewstate to a SQL Server table. The character count of my viewstate is 82,000+ characters. It pretty darn big. I converted the C# code to VB using a converter, but I do not understand where I am suppose to paste the code. Could you please let me know. I will continue to research on this end. Once I know where to paste the converted code I can save on the server.

Once I save to the database I will try and determine whether a PC connection and mobile broadband connections are quicker. I hope so.

Thanks, Bruce


Vijayendra
on June 06, 2006

This artical is the best I have read on View State. This artical is short and to the point without missing a single point.


Ankit Goel
on June 12, 2006

This article is very helpful...specially how can we encrypt our Viewstate.

Ankit


Jeremy
on June 15, 2006

Best article on viewstate I've read so far, and I've read a alot of them.


neha
on June 23, 2006

Hey Milan

Gr8 article!!!
Awesome!!!
fantastic
too gud
i hv run out of words

thnx u took ur precious time to write sch an article....

neha


parag
on June 26, 2006

The Document was Excellent.


mark
on July 19, 2006

Excellent document, but the key generator is a little flawed ;) Is any one really going to believe that you aren't saving the output somewhere? Do you really want your secret keys travelling over HTTP? When it comes to security I'm a little paranoid!


Milan Negovan
on July 20, 2006

I hear you, Mark! That's why I give out source code of this tool so you can run it locally ;)


Brian
on September 21, 2006

Best article I've ever read regarding ViewState - saved me from sinking into a Deep Pit of Great Sadness today dealing with a DataGrid on a Web Farm - Thanks for taking the time out to share what you've learned!


wendi
on October 11, 2006

great article. but have question...

i have a user controls that is comprised of textboxes, checkboxes, listboxes, and dropdownlists. on postback, i get the values of each field with request.form("..."), but afterwards, rebuild my control and assign new values. when the page/control loads, it's values at the time of postback render to the client, instead of the values i changed after postback. i've tried to clear viewstate after postback with no success. any suggestions?


R.Naresh
on October 13, 2006

Thankyou Very Much, this has become my Best material in ViewState topic. U made this very simple thanks once Again


srinivas
on November 08, 2006

Best article I have ever read on viewstate - really good work. Thanks for putting in the effort.


Alla
on November 17, 2006

I am so confused. For the last couple days I am trying to solve an issue with checkboxes in GridView. On Page_Load I read data from a file and display it in a GridView, which has Template Field with a checkbox. When I select a different file to load, all the checkbox are checked/unchecked as they were for the first file. I don't want them to be like this. I want them to go to their initial values. I tried both to enable/disable ViewState for the checkbox and for the GridView and for the page. Nothing changes. The checkboxes remain the values from after the first file-load. What do I do wrong? Or maybe this is not ViewState issue at all.
Appreciate any piece of advise.


John A. Davis
on November 17, 2006

Like everyone else, I think this article is great. I wasn't even looking for this info, having given up on trying to reduce Viewstate on my Admin form. But now I know I can save it in a database and solve the roundtrip overhead I've been incurring.

thank you


Milan Negovan
on November 26, 2006

Alla, when it comes to Grids and their derivatives, view state issues tend to get complicated. Do you think you can send me a sample of what you're trying to achieve so I can take a look at it?


Robert
on November 30, 2006

Thats a wonderful one on View State. Very useful! Thanks for the effort.


Vishwanath Paibir
on March 15, 2007

Job Well Done. :-) Very nice article. I really enjoyed it reading. And it also cleared lot of my doubts about view state.

Regards
Vishwa


Carlos
on April 01, 2007

Thanks for share this :). I learned a lot, and cleared many doubts about Viewstate, btw Viewstate size is not a problem 4 me, since I'm using blowery httpcomression :D


jason
on May 17, 2007

What you're saying about ViewState is quit circular. If you turn Viewstate on, on your sample page and compare the size vs when it's turned off, you'll see the ViewState is exactly the same size. All you've said is, "Some controls don't use ViewState, so you can turn it off". But, if the controls aren't using ViewState, why bother turning it off?


KingWahWah
on May 29, 2007

Also useful for non-devs like me.

Very well explained.

Thanks


Nagalaxmi
on July 28, 2007

This is really cool cool one. The presentation is cool with subtle sense of humour. Excellent.


Jarrett
on August 07, 2007

Just messing around with this code, because I've been looking for a way to turn an instance of StateBag into a viewstate string. Your article says that LosFormatter.Serialize takes an instance of a StateBag, but I tried doing just that and it fails, saying that StateBag is not serializable.

Does LosFormatter.Serialize really take an instance of StateBag, or is the 'object' parameter passed to SavePageStateToPersistenceMedium a black box whose type is some magical internal object that can't be accessed normally?


Milan Negovan
on August 08, 2007

Jarrett, anything you put in view state should be serializable because, ultimately, view state is a chunk of text. If you store a custom class or collection, make sure you mark it as [Serializable].


Jarrett
on August 09, 2007

I take it, then, that StateBag is not serializable. I then have to question the truth of this paragraph in the article: "The Serialize method is the one that converts an instance of StateBag (second parameter) and writes it into a Stream or TextWriter. The Deserialize method performs the opposite task. It builds an instance of StateBag from a base64 encoded string, a stream or a TextReader."


Milan Negova
on August 09, 2007

The StateBag class, as you can see in Reflector, is quite simple. It's like a dictionary. It doesn't have a problem with anything you put in... untill the serializer takes what's in the StateBag and tries to flatten it into a string of text. So that statement is correct. :)


Jarrett
on August 10, 2007

The following code:

StateBag sb = new StateBag();
sb["foo"] = "bar";

StringBuffer buffer = new StringBuffer();
StringWriter writer = new StringWriter(buffer);
LosFormatter lf = new LosFormatter();
lf.Serialize(writer, sb);
writer.Close();

Fails on lf.Serialize, because StateBag itself is not serializable, contents notwithstanding.

If the object passed to SavePageStateToPersistenceMedium really is a StateBag, I'd expect any attempt to serialize that object with LosFormatter to fail, but it apparently doesn't. So either I'm doing something wrong, or the object passed to SavePageStateToPersistenceMedium really isn't an instance of StateBag.


Milan Negovan
on August 10, 2007

I'm not sure what you're trying to do, but your sample looks very similar to the technique Dino Esposito presented in an article of his a while ago. In the SavePageStateToPersistenceMedium method the state bag is actually serialized.


Jarrett
on August 10, 2007

That example looks very similar to yours. He calls the parameter "viewStateBag" but the type StateBag is never actually used, so I have no idea if that object really is an instance of StateBag or not. In fact it could be just about anything. It's completely opaque.

What I'm actually trying to do is build an automated web site testing app. I have an input file which lists some control states (i.e. the control name and the type/value it holds). I want to build up the state bag and convert it to a viewstate myself, since I'm querying the site programmatically. So, I create an instance of StateBag, fill it with the control values, build a viewstate string out of it, set that as the __VIEWSTATE variable and send the HTTP request. The problem is going from a StateBag to a viewstate string. Is there some other way to go about what I want to do?


devendra
on September 22, 2007

execellent article for beginer like me to understand the theory.
I am developing an application for my company which is running great for desktop version but as company is expanding i have recommended use of asp .net. It would be great if you can send me link of a tutorial that will demonstrate the mentioned subject


Milan Negovan
on September 24, 2007

Devendra, the article is a tutorial of a sorts. Other than that, there's no view state tutorial per se.

Is there a specific subject you have in mind?


zhouhuanjia
on December 18, 2007

The ASP.NET page has its view state turned off completely. See how it maintains text and selections once you click Submit. Scroll down to "Form Collection" to see what was posted. ASP.NET restored these values automatically!
============================
--The ASP.NET page has its view state turned off completely. --
How Do I Disable View State?


Priyank
on December 20, 2007

Very Useful article for viewstate...
thanks...


Josh Stodola
on January 02, 2008

Fantastic article, Milan. It helped answer a question I was pondering today. Thanks!


sgoll
on February 05, 2008

This is one of the best articles I read online. No crap, just useful information. Very well presented.

Thanks.


Soumya
on May 21, 2008

Thank you.
It is an excellent article on View State.


Mark
on June 19, 2008

If only Microsoft was able to produce documentation written so clearly. Refreshing also to see a frank admission of limitations and flaws, with useful workarounds, rather than the Microsoft way of labelling poor design as "feature rich" and problems the result of competitors trying to limit their "freedom to innovate".

And yes, Borland and Pascal were the good ol' days...


Svend Tofte
on July 18, 2008

Jarrett, the "object viewState" which is passed in via the SavePageStateToPersistenceMedium is actually a Pair.


Stefan
on October 10, 2008

Thanks!
Finally I found a good article on View State.


Chintan
on October 15, 2008

Do you have benchmarking results of using page with and without viewstate.Can you provide the same if you have it.


Milan Negovan
on October 15, 2008

Chintan: no, I haven't benchmarked it.


Syed Shees Abidi
on November 25, 2008

Good article i have recommended it to my friends also


ASPNETCoder
on December 01, 2008

Very very good explaination of ASP.NET view state. one small question what will happen if i turn off the view state at applcaiton level and then try to use the view state for one of the control in a page ??? thanks


Milan Negovan
on December 02, 2008

I believe none of your controls will have view state.


Vijay Kumar
on December 20, 2008

This article gave me an insight into View State from scratch.Its Simple to Understand and complete.I Enjoyed learning and IThank You Whole Heartedly Very Much.


fargii
on January 12, 2009

Although the article relates to an older version of .NET, the discussion is very thorough and well presented. I learnt something new. Thank you.


Karlton Kemerait
on February 02, 2009

Thank you very much for this complete, easy to understand and yet technical article. I wish all articles were written like this.

http://designlunacy.blogspot.com


chandan bora
on April 10, 2009

Really this is a good article, which helps a lot for begineers as me as well as developer.
Thanks.


Gokul McNg
on October 23, 2009

I really appreciate your article.Great!!


Seraj
on October 27, 2009

It's Nice article But...
Web is stateless and server does not know the next request.
and You told
TextBox retains its value across PostBack when viewstate is False
From where it gets value?


Milan Negovan
on October 27, 2009

Seraj, please re-read the article. It explains it.


John Dyer
on December 07, 2009

Very much enjoyed your article. Learned much. Would appreciate your input on problem I am having. I cannot tell if problem is that of viewstate or session state, I believe it to be session state. Since introduction of ISA server into the mix (server which we have no control over), we are experiencing what I believe to be session timeouts within a minute of so when a postback should occur. We just have the one web server in our environment. Sometimes the web app works longer and sometimes it times out quickly. All I get is a white blank screen. A view source shows the following:






Any pointers on where to look to resolve this issue would be greatly appreciated.

Thanks!

John


Milan Negovan
on December 16, 2009

John, I'm really not sure how introduction of an ISA Server may cause this.


raghu
on February 04, 2010

Excellent Article..My hearty wishes to Author.
no more book reference or web search needed for viewstate here after.Very Good way of explanation.I request the author to give more
artilcles on latest frameworks.


prasanna Y
on February 08, 2010

Thanks!
Finally I found a good article on View State.


DanG
on February 24, 2010

Very interesting, and enjoyable to read too!


Thomas Hansen
on March 23, 2010

Your article is really great, but it contains one bug if you use your code in ASP.NET2.0, since it won't serialize ControlState accurately if you're dependent upon controls that are using ControlState. Or rather, to be correct, ASP.NET's Save/LoadStateToPersistenMedium contains a bug in fact ... ;)

Errata is here; http://ra-ajax.org/how-to-store-viewstate-on-the-serve


Milan Negovan
on March 28, 2010

Thomas, thank you for heads-up!


Anil Reddy
on April 12, 2010

Thanks for posting such an awesome article. Pointed out all the aspects abt View state. U rock...Keep up the good work.