Welcome to AspAdvice Sign in | Join | Help

Alessandro Gallo

.NET & Beyond
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();

      ddlCultures.DataSource = Globalization.GetOrderedCultures();


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.

Posted: Wednesday, January 21, 2009 9:33 AM by Garbin


Dominic Pettifer said:

I've always done this because without the IsPostBack check your control gets re-databound and you loose the selected value, especially if a form validation error kicks in.

I guess putting it in the Init event would work (as ViewState hasn't kicked in yet). But then it's potentially making two database calls for every control, even if the page validates and you're Response.Redirected elsewhere (eg. success screen). I guess you would have to way up the  slightly lower page size against the increase in database activity.

# January 21, 2009 7:17 AM

Garbin said:

I don't see ViewState as a solution to database activity issues. Cache seems better suited for that.

# January 21, 2009 8:46 AM

DotNetKicks.com said:

You've been kicked (a good thing) - Trackback from DotNetKicks.com

# January 22, 2009 3:55 AM

ReBitting said:

ViewState Handle-with-care

# January 22, 2009 3:58 AM
New Comments to this post are disabled