Scott Hanselman

Moving ViewState to the Session Object and more Wrongheadedness

February 28, '04 Comments [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
Sponsored By
Hosting By
Dedicated Windows Server Hosting by ORCS Web

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