Skip navigation.

ASP.NET State Management: View State

Comment permalink 1 John Spurlin |
This is the best article on viewstate I have read. It is concise and thorough.
Comment permalink 2 andy |
I've been searching for weeks for a document like this. well done. thanks!
Comment permalink 3 Robert Pegg |
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.
Comment permalink 4 Niranjan Srinivasan |
Very lucid explanation. Keep up the great work.
Comment permalink 5 Don Almeida |
Is there a size limitaiton on ViewState?
Comment permalink 6 Milan Negovan |
I don't think there's a limitation.
Comment permalink 7 Bids |
Its a great article on View state.
Comment permalink 8 Damien McGivern |
I've always been wary of view state; now I'm scared of it! Great article.
Comment permalink 9 Lars Kjeldsen |
Best article I have ever read on viewstate - really good work. Thanks for putting in the effort.
Comment permalink 10 Leon |
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.
Comment permalink 11 Milan Negovan |
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.
Comment permalink 12 Morgan Skinner |
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!
Comment permalink 13 Milan Negovan |
Glad you've found it helpful, Morgan. ;)
Comment permalink 14 Naveen |
Very lucid, very comprehensive, liked it a lot!
Comment permalink 15 bala |
Its very helpful.
Comment permalink 16 Rosi Reddy |
This is the excellent article. I have ever seen this much good article on view state... Keep it up.....
Comment permalink 17 Sirisha |
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
Comment permalink 18 Sirisha |
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]
Comment permalink 19 Milan Negovan |
Sirisha, be reasonable. This really isn't a dicussion forum here. Ten page downs of souce code is more suitable for ASP.NET Forums.
Comment permalink 20 Burt |
This is the best article on ViewState vs Session that I have seen to date! Keep up the good work.
Comment permalink 21 Mike Ogden |
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! :)
Comment permalink 22 Milan Negovan |
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.
Comment permalink 23 Bryan Wang |
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,
Comment permalink 24 Milan Negovan |
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.
Comment permalink 25 JfK |
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.
Comment permalink 26 Milan Negovan |
I wouldn't go that far because the page "checksum" is there for a reason.
Comment permalink 27 JfK |
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)
Comment permalink 28 Ruchita |
This is the best article on viewstate i have read so far....
Comment permalink 29 Orlin |
Fantastic article! One of the best articles I have read in my life.
Comment permalink 30 Erik |
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'?
Comment permalink 31 Milan Negovan |
I'm not 100% sure how the bare-bones checksum is built, but there's really no way of getting rid of it completely.
Comment permalink 32 Kaushal |
Really an exceptional article on viewstate. Tons of thanks to Milan Negovan to provide such useful information.
Comment permalink 33 Bruce Hemmerich |
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
Comment permalink 34 Vijayendra |
This artical is the best I have read on View State. This artical is short and to the point without missing a single point.
Comment permalink 35 Ankit Goel |
This article is very helpful...specially how can we encrypt our Viewstate.

Ankit
Comment permalink 36 Jeremy |
Best article on viewstate I've read so far, and I've read a alot of them.
Comment permalink 37 neha |
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
Comment permalink 38 parag |
The Document was Excellent.
Comment permalink 39 mark |
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!
Comment permalink 40 Milan Negovan |
I hear you, Mark! That's why I give out source code of this tool so you can run it locally ;)
Comment permalink 41 Brian |
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!
Comment permalink 42 wendi |
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?
Comment permalink 43 R.Naresh |
Thankyou Very Much, this has become my Best material in ViewState topic. U made this very simple thanks once Again
Comment permalink 44 srinivas |
Best article I have ever read on viewstate - really good work. Thanks for putting in the effort.
Comment permalink 45 Alla |
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.
Comment permalink 46 John A. Davis |
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
Comment permalink 47 Milan Negovan |
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?
Comment permalink 48 Robert |
Thats a wonderful one on View State. Very useful! Thanks for the effort.
Comment permalink 49 Vishwanath Paibir |
Job Well Done. :-) Very nice article. I really enjoyed it reading. And it also cleared lot of my doubts about view state.

Regards
Vishwa
Comment permalink 50 Carlos |
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
Comment permalink 51 jason |
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?
Comment permalink 52 KingWahWah |
Also useful for non-devs like me.

Very well explained.

Thanks
Comment permalink 53 Nagalaxmi |
This is really cool cool one. The presentation is cool with subtle sense of humour. Excellent.
Comment permalink 54 Jarrett |
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?
Comment permalink 55 Milan Negovan |
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].
Comment permalink 56 Jarrett |
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."
Comment permalink 57 Milan Negova |
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. :)
Comment permalink 58 Jarrett |
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.
Comment permalink 59 Milan Negovan |
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.
Comment permalink 60 Jarrett |
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?
Comment permalink 61 devendra |
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
Comment permalink 62 Milan Negovan |
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?
Comment permalink 63 zhouhuanjia |
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?
Comment permalink 64 Priyank |
Very Useful article for viewstate...
thanks...
Comment permalink 65 Josh Stodola |
Fantastic article, Milan. It helped answer a question I was pondering today. Thanks!
Comment permalink 66 sgoll |
This is one of the best articles I read online. No crap, just useful information. Very well presented.

Thanks.
Comment permalink 67 Soumya |
Thank you.
It is an excellent article on View State.
Comment permalink 68 Mark |
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...
Comment permalink 69 Svend Tofte |
Jarrett, the "object viewState" which is passed in via the SavePageStateToPersistenceMedium is actually a Pair.
Comment permalink 70 Stefan |
Thanks!
Finally I found a good article on View State.
Comment permalink 71 Chintan |
Do you have benchmarking results of using page with and without viewstate.Can you provide the same if you have it.
Comment permalink 72 Milan Negovan |
Chintan: no, I haven't benchmarked it.
Comment permalink 73 Syed Shees Abidi |
Good article i have recommended it to my friends also
Comment permalink 74 ASPNETCoder |
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
Comment permalink 75 Milan Negovan |
I believe none of your controls will have view state.

Submit your comment

Please enter only text since all HTML tags except hyperlinks will be stripped. Hyperlinks will become live links. Any comments with flaming or offensive language will be deleted. Be courteous to other posters. Thank you.

Your name (required):
Your email (optional):
Your site's URL (optional):
Enter this number
Type in the number above:
Comment (required):