ViewState Bloat

Troubleshooting ViewState errors is a big pain! I have one end user who randomly is getting the server error “The state information is invalid for this page and might be corrupted.” The stack trace shows “Format Exception: Invalid length for a Base-64 char array or string.” So the questions become how big is the ViewState, what does it contain and how can we make it smaller?

How big is my ViewState?

Assuming that web.config > configuration > system.web > pages > maxPageStateFieldLength is default, the ViewState is stored in a single hidden input value and is base-64 encoded and encrypted (also default).  We can get the length of the base-64 string using this JavaScript from the browser developer tools console.

document.getElementById("__VIEWSTATE").value.length

I was seeing lengths in excess of 79,000.

What does my ViewState contain?

By setting web.config > configuration > system.web > pages > viewStateEncryptionMode=”Never” and reloading the page we can now decode the base-64 string from within the console. I wouldn’t recommend disabling encryption on a production website.

atob(document.getElementById("__VIEWSTATE").value)

Mine contained the values of every control including the data bound by the SQL Data Source. Since my page contains a FormView with many fields and even GridViews there is a lot of data.

How can I make my ViewState smaller?

We can disable controls from using ViewState by setting the  EnableViewState property to “False” on each control. I did this a my FormView expecting an error or paging to break but I can’t tell a difference and my ViewState has shrank to less than 500 characters. (I will update if after further testing I find a downside)

I tried many suggestions I found online. Some seem to do nothing and others cause more problems. You have to have ViewState enabled to use certain controls or events. So it doesn’t make sense to disable completely. Since the client can’t modify the ViewState without causing a server error why does the client need a copy? I tried one suggestion of overriding methods and storing the state in the session but while I like this idea I could not get it to work.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *