All posts

How wrong custom ViewState handling may harm more than help

As some of us have found last Friday this article in MSDN about how to store your ViewState in Session is totally wrong. Using the Reflector you can find very easily that ControlState will be erased if you access more than once PageStatePersister.

The correct implementation should be:

     PageStatePersister _pers;
     protected override PageStatePersister PageStatePersister
     {
         get
         {
             if (_pers == null)
                 _pers = new SessionPageStatePersister(this);
             return _pers;
         }
     }

How about overriding SavePageStateToPersistenceMedium / LoadPageStateFromPersistenceMedium?
If you do this you should update your PageStatePersister or you will miss the ControlState once again. Example:

protected override object LoadPageStateFromPersistenceMedium()
{
     object state = THESTATE;
     if (state is Pair)
     {
         Pair statePair = (Pair)state;
         PageStatePersister.ControlState = statePair.First;
         PageStatePersister.ViewState = statePair.Second;
     }
     return state;
}


Both implementations are widely spread so be careful!

Comments  2

  • 26 Sep, 05:10 PM

    Thanks for the info :)
    I am considering implementing something like this as ViewState is building up and I have alot of RAM on the sever. No doubt I would have come across the MSDN article when googling for solutions and assumed it was right.

    comment by: Alex
  • 3 Jul, 09:15 PM

    Thanks for that, extremely helpful - i would say perfect.

    comment by: Sohail
Post a comment!
  1. Security image