Tuesday, October 09, 2007

Completely Disabling ViewState in an ASPX Page

As an unabashed ASP.NET novice, I like to ease my way into new things -- the less unknown variables that enter the picture, the easier it is to identify the source of any problems that arise. And one of these new things that I don't yet feel comfortable with is ViewState.

Yes, it's great that you don't have to worry about repopulating your page's data, but there are still plenty of problems that can occur if it's not used properly. One of those issues that I've already run into is page bloat: if there's a lot of information that needs to be "remembered" across round-trips to the server, the information stored in the hidden, client-side ViewState variable will be massive.

I forget where I gleaned this information from, when I figured this out a few months ago, but I'm posting it here before I forget. I completely disable ViewState in an ASPX page's codebehind (C# v2.0) by adding three methods at the top of the class declaration, before the Page_Load() method:


public partial class yourClassName : System.Web.UI.Page {
#region Completely disable page viewstate.
override protected void SavePageStateToPersistenceMedium(object viewState) { }

override protected object LoadPageStateFromPersistenceMedium() {
    object returnValue = null;
    return (returnValue);
}

override protected object SaveViewState() {
    object returnValue = null;
    return (returnValue);
}

#endregion

protected void Page_Load(object sender, EventArgs e) {
    // Your normal ASPX.CS code
}
}


I'm still not aware of all the potential repercussions of using this, so please feel free to comment if you run into any problems.

No comments: