Scott Hanselman

Moving ViewState to the Session Object and more Wrongheadedness

February 28, 2004 Comment on this post [5] Posted in ASP.NET | ViewState
Sponsored By

Some folks didn't agree with my recent comments on ViewState.  That's cool, it's good to disagree.  The truth is no doubt somewhere in the middle.  My conclusion, and your take away should be this:

  • ASP.NET sucks exponentially LESS than any previous Web development technology
  • ViewState can be used for evil, but if you understand it, it can be VERY useful
  • ASP.NET is so powerful that it can enable you to be an incredibly bad programmer FASTER THAN EVER.  Don't program by coincidence. 
  • Know the bytes that leave your web server and what they are for.  Look inside the Viewstate with either Web-based Paul Wilson's ViewState Decoder, or Fritz Onion's Win-Form ViewStateDecoder.
  • Buy Fritz's book.  Seriously.

Now, that being said, I've also seen lots of talk on the 'Net about overridding default behavior and storing ViewState to another location, like the Session object.

Sadly, I saw lots of code on the USENET like this (Here's a VB.NET Example, but the language is an implementaton detail):

Public Class PageViewStateSession
    Inherits System.Web.UI.Page
  Protected Overrides Function LoadPageStateFromPersistenceMedium() As Object
    Return Session("ViewState")
  End Function
  Protected Overrides Sub SavePageStateToPersistenceMedium(ByVal viewState As Object)
    Session("ViewState") = viewState
    RegisterHiddenField("__VIEWSTATE", "")
  End Sub
End Class

What's wrong with this?  Apparently not enough to keep it off the 'Net, but enough for me to remind you:

Scott's Rule of Programming - Rule# 0x3eA
Just because code is on the Internet doesn't mean you should cut and paste it into your production system.  Do you chew gum you find on the street?  Give code you find on the 'NET the same amount of attention you'd give advice scrawled on a public bathroom wall.

What's wrong with the code?  Well, it uses the SAME KEY to store the ViewState in the Session object, forgetting that ACTUAL ViewState stays with the page 'instance.'  To use an anology you can relate to, just pick a random variable in any application you wrote and slap the keyword static on it.  Think it will work?  If it does, I wonder how long it will? 

If you store ViewState in the Session object in this way, you are assuming the user will access only one page at a time, and you may confused other pages in their attempt to load values from Bogus ViewState.  More importantly, what happens if the user opens new browser window, and starts accessing DIFFERENT pages but sharing the same session.  Well, you get the idea.

Some folks got around this by adding the requested page to the ViewState key:

Session[this.Request.Path + "-VIEWSTATE"] = ViewState;

But remember that the actual code in ASP.NET (more or less, via Reflector) does this:

text1 = this._requestValueCollection["__VIEWSTATE"];

It pulls the ViewState from the request NameValueCollection (including the Form collection, etc).  Each 'instance' of a page has it's own ViewState.   Then in OnFormRender, they:

writer.Write("__VIEWSTATE");
writer.Write("" value="");
this._formatter.Serialize(writer, this._viewStateToPersist);

So the question of the day is, how to move ViewState in to the Session Object (conveniently ignoring the additional memory consumption and the fact that the objects you store in the session will not expire, eh?), but still allow a user to have TWO browser windows up acting on the same page at the same time?  You'd need to store a unique index key in a Hidden Field to act as a lookup into the Session object rather than using the name of the page.

Here's the only even-close-to-clever example I could find via Google, and it has a LOT of limitations and a LOT of moving parts, and may have some threading problems. (Remember the bathroom wall!)

Even More Conclusion

Seems to me that this is a lot of work to do to save a fer bytes when someone could just:

  • Learn what needs ViewState and what doesn't and use it selectively.  It's NOT required for 90% of things, and you can usually get it down to a very small size.
  • Spend less time writing wrongheaded plumbing code to replace ViewState, and instead learn how to use it effectively and efficiently.  Read that last sentence again.
  • If you're that worried, use HttpCompression (seriously, if you're not using Http Compression, what's your excuse?)

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Hosting By
Hosted in an Azure App Service
February 29, 2004 2:26
I've actually talked to some developers who aren't allowed to use session state and have to use the viewstate object because "session state doesn't scale" according to the senior developers at the company (think one of the largest health providers in the us). He said he used some internal apps that had over 150k of data in the viewstate.

They were also told that they should store all connection string info in the global.asax file, and other "it was a best practice for ASP, it must be the same for ASP.NET" type issues.
March 01, 2004 20:15
I once (mistakenly - didn't anticipate scaling) stored 10MB in the ViewState. IE (and my computer along with it) was frozen for a good 30 minutes. That was bad. But I agree, when used intelligently (as opposed to how I was using it), it is great.

BTW - does anyone else have problems with relative URL's in their RSS readers? I tried to click through to the link for HttpCompression from Outlook (intraVNews) and it didnt' resolve to the full address. Is that a problem with the RSS spec, or just an implementation issue with intraVNews?
June 08, 2004 19:54
After taking the C# code from http://authors.aspalliance.com/robertb/articles.aspx?articleId=2 and filtering it through http://www.kamalpatel.net/ConvertCSharp2VB.aspx and then changing some long and short datatypes - I found Robert Boedigheimer's idea to be quite simplistic compared to some of the complexities of the blowerly compression module (reference http://www.hanselman.com/blog/PermaLink.aspx?guid=f18db706-05b2-4721-a6b4-76a3a28448f8).

I think the 'bathroom wall' argument should go equally for the blowery code as for the Boedigheimer code and that it would be a logical leap to conclude that every bit of information found on the net pertaining to code is a bad idea. That aside, you did have some valid points about thinking about what is put where. Thanks.
July 01, 2005 0:02
Can I plug my own after the fact viewstate displayer control? Fritz utility never worked for me.

http://www.pickabar.com/blog/archives/2005/05/viewstate_displ.html
March 13, 2006 9:13
I got the error "The viewstate is invalid for this page and might be corrupted." Description of my error is here http://forums.asp.net/1223520/ShowPost.aspx I think above code wil help me to resolve this problem but Still i am getting this error how to resolve this please help me in this matter

Please you can reply on my post also

Comments are closed.

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.