I Don’t Miss ViewState
May 16, 2010 3 Comments
I’ve been working with ASP.NET MVC for the last year and I don’t miss webforms. The one thing about webforms I miss the least is ViewState.
It’s a Hack
Hidden HTML fields were never intended to hold so much data. Persisting data in the page this way is Ugly, Expensive, Confusing, and Hard to Test.
It’s Ugly
ViewState is this ugly blob of Base-64 encoded data:
<input type=”hidden” name=”__VIEWSTATE” value=”aHR0cDovL3d3dy5jb2Rlcm9zZXR0YS5jb20vYmFsbHB1enpsZQ==” />
It’s Expensive
ViewState is processed on every postback. This means it has to be sent, parsed, processed, updated, and re-sent with every request. Not good for performance!
It’s Confusing
I can’t tell you how many StackOverflow and forums posts I’ve seen about dynamic controls and ViewState. If you don’t add dynamic controls at just the right point in the page lifecycle, ViewState breaks.
It Uses Magic Strings (So It’s Hard to Test)
ViewState["MyMagicString"] is a typo-prone way to address data. Strongly-typed Views in ASP.NET MVC are so much easier to work with and much more testable.
The MVC Way
MVC doesn’t even try to match ViewState as a feature. ViewState is a stateful paradigm layered on top of a fundamentally stateless protocol: HTTP. Rather than the hybridized hack of packing a huge encoded graph into a hidden field, MVC says:
“If you want to persist state, do it on the server using a Model.”
You can use Session state or TempData on the server and javascript or cookies at the client to store pointers, but actual data should be persisted by one thing- the Model. The MVC rendering pipeline relies on Models (or ViewModels) to retain and provide the data that populate Views. If you change the state of a control, the data is updated in and persisted through the Model, preferably by a loosely-coupled persistence implementation. This is a much cleaner, architecturally sound method for dealing with state over a stateless delivery protocol.