ViewState: Handle with care
I’m refactoring an ASP.NET application and I’ve already found several times – too many – code similar to the following:
<asp:DropDownList ID="ddlTimeZone" runat="server" />
<asp:DropDownList ID="ddlCultures" runat="server" />
protected override void OnLoad(EventArgs e)
{
if(IsPostBack == false)
{
ddlTimeZone.DataSource = GetTimeZones();
ddlTimeZone.DataBind();
ddlCultures.DataSource = Globalization.GetOrderedCultures();
ddlCultures.DataBind();
}
base.OnLoad(e);
}
This code is going to serialize several kilobytes of ViewState data in the page ( > 10Kb with both controls declared). There’s almost never a valid reason to increase the page size in this way.
A possible fix:
1. Disable ViewState on the controls by setting EnableViewState=”false”. You avoid serializing bound data to the page.
2. Get rid of the IsPostBack check and move the databinding logic in the Init stage. You bind the controls every time, but you don’t override the posted value (which hasn’t been loaded, yet). SelectedValue still works.
A very good reference for ViewState handling is this post by Dave Reed.