Nov 06 2008

The ASP.NET ViewState…

Published by nick at 3:42 pm under Work

The ViewState in ASP.Net is one of those weird and wonderful things that Microsoft obviously thought was a good idea at the time. Granted, it is quite useful but as with all things like that, it comes with a price – and a fairly hefty one at that if not used sensibly.
The problem is this – by default ASP.Net enables the ViewState and, by default, the majority of the asp controls use the ViewState to some extent. Usually this is quite handy, as it means you don’t have to worry about storing data between postbacks – the ViewState does this for you.
In my limited experience, the only time this becomes is a problem is when you’re using the GridView control and need a relatively small page size. The GridView control has a tendancy to store all of its data in the viewstate as well as in HTML as normal. Now, if you’re likely to be modifying the data in the GridView somehow, this is fine. But if you’re not, then you’ve got all of that data twice! This can then result in pages upwards of 100kB!
There is light at the end of the tunnel, however. Microsoft, helpfully, included a parameter that you can set in most controls to stop them using the ViewState – EnableViewState. Set that to false, and the control won’t use the ViewState. I did this recently at work, and got a page with a ViewState of over 100kb, down to 2kb.
It’s also worth paying attention to what you’re storing in the ViewState using the Code Behind, this can be another big killer if you’re trying to save Database calls for example. Of course, in some situations this may be the best option – but not always. In some cases it may actually be faster, and more beneficial to your users, if you get the data from the database again, instead of from the ViewState.
So, what’s my point? Well it is simply this – if you don’t need the ViewState on a Control, then turn it off. Your pages will load quicker, your server bandwidth will get used up slower and everyone will be happy!

No responses yet

Leave a Reply