How wrong custom ViewState handling may harm more than help

Tuesday, September 25, 2007 by Vladimir Enchev | Comments 2
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!

2 Comments

  • Alex 26 Sep
    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.
  • Sohail 03 Jul
    Thanks for that, extremely helpful - i would say perfect.

Add comment

  1. Formatting options
       
     
     
     
     
       
  2. (optional, emails won't be shown on public pages)
  3. (optional)