7/11/2007

ASP.NET : Killer Viewstate Invasion

"They can hold all the peace talks they want, but there will never be peace in the Middle East. Billions of years from now, when Earth is hurtling toward the Sun and there is nothing left alive on the planet except a few microorganisms, the microorganisms living in the Middle East will be bitter enemies."
-- Dave Barry

Recently I was "trying out" some pages on my latest creation, BlogMetaFinder.com, and I noticed that paging of the Gridview on the main page was slow. Long story short -- View Source and I've got 975,000 bytes (In EditPlus, "Edit / Character Count") mostly all ViewState. "Yikes", I thought, "if I turn this off I'm gonna have to do custom paging with this SQLDataSource and all kinds of extra stuff". The data source is a little less than 2500 rows now, which is kind of "on the edge" of where you might not want to use the default paging in a GridView.

Anyway, I turned off ViewState in that Page and also in the Master, which was also contributing to FVS (Fat ViewState) and everything still works fine. I've written about this a couple of times (here's one article) and I could kick myself for forgetting about it.

Custom paging is a lot easier to do now with SQL Server 2005 because you've got the ROW_NUMBER feature, and there is plenty of sample code on how to do it. SQLDataSource doesn't play well with it though, you need to use the ObjectDataSource. Obviously, if you aren't using ObjectDataSource and you need to put in custom paging, there's going to be some serious refactoring going on...

Bottom Line? Watch that ViewState. Most of the time, you don't even need it. Turn it off selectively on various controls. Lightens up the page quite nicely. ViewState is downright evil!