How to put ControlState into ViewState and how to put ViewState into session

It’s a common problem, that your viewstate is bloating up under heavy usage (complex data editing scenarios with multiple grids enabling editing, etc). ASP.Net 2.0 comes up with a handy solution for such cases by letting you easily redefine your PageStatePersister in your page with (under .NET 1.0/1.1 this could be done using LoadPageStateFromPersistenceMedium and SavePageStateToPersistenceMedium):

    protected override PageStatePersister PageStatePersister
    {
        get
        {
            return new SessionPageStatePersister(this);
        }
    }

After changing this (and applying a custom base page for all my pages with:

 
<pages pageBaseType=”PageBase” />
 

for this to work it is needed to derive all your aspx pages from that page!)

I got the result from ~3500 viewstate bytes to ~1500 viewstate bytes. But what can I do with that 1500 bytes? What is in it? I started ViewStateDecoder 2.1, and checked into it, what I saw was surprising: all usual viewstate data was wiped out, but there were still the controlstate! So it’s not the same as the PersistanceMedium calls as they were formerly… How to get rid of that 1500 byte? After using the Reflector a bit I found out, that all depends on a browser capatibility called RequiresControlStateInSession, when it’s set to true, than the controlstate is persisted into the session as well. Last question was: how to let the system know, that my browser has the RequiresControlStateInSession capatibility? It’s easy with the new syntax for browserCaps:

  <system.web>
    <browserCaps>
      <case>
        RequiresControlStateInSession=true
      </case>
    </browserCaps>
  </system.web>

And the day is saved, now I have a viewstate of a 57 bytes, which contains a pair of a boolean and an ID 🙂