I was trawling through new posts on the ASP.NET blog site and came across this one from Tess (who is someone I should probably know but don’t…). What I found interesting (as well as the post which is excellent) was the first comment:
“When will MS simply drop the Viewstate completely? This is a good example of a solution to a problem that shouldn't be a problem to begin with. “
This got me to thinking, ViewState has gotten a really bad rap over the years (with notable exceptions). Let’s look at what ViewState actually is and why it might not be the villan it’s often painted out to be…
What is ViewState…at it’s simplest it’s a hidden field which contains data about the controls currently on the page. Really, that’s it…now it does this pretty cleverly, serializing a whole bunch of stuff into a Base64 encoded string (which can also be encrypted, validated etc…).
For those of us who wrote web apps back in the dark ages i.e., before ASP.NET, we remember the days where we had a bunch of hidden fields used to track changes in a page, and it was frankly a pain in the ass…it was far more transparent but a lot of grunt work just to track if a field’s value had changed / store some additional data in the page for use in postback. ViewState solves that problem pretty nicely actually.
So, what’s the problem people have? Two things:
1. people misuse it; it’s partly our fault and partly theirs.
From ‘Truly Understanding Viewstate’:
CASES OF MISUSE
a. Forcing a Default
b. Persisting static data
c. Persisting cheap data
d. Initializing child controls programmatically
e. Initializing dynamically created controls programmatically
Now, as I said it’s not entirely their fault…ViewState is enabled by default…if you bind a bunch of data to a DataBound Control then you’ll get a huge amount of ViewState serialized to and from the browser each time, it’s not that easy to figure out what having no ViewState will break / just enable it for certain controls and not others (which is what ControlState lets you do…just not for existing controls).
At it’s core the problem ViewState really has is that it’s a Leaky Abstraction; it’s ALMOST there but doesn’t quite hit the sweet spot nowadays…
So, how do you use ViewState correctly…what can you do to avoid the pitfalls?
Stay tuned!