Serializing viewstate to object
In an earlier article, concerning a refactoring to a State machine, I stated the problem of passing the entire viewstate to the state machine because of the need for some viewstate items.
Actually I needed a total of 5 viewstate items. So passing the entire viewstate was definitely not a good idea. After reading some stuff about serialization I solved the problem.
Let me explain the steps.
- Create an class which contains the needed properties
- Override LoadViewState and SaveViewState in the page
- Load the object from the viewstate in LoadViewState
- Save the object in SaveViewState
- Pass the object into the state machine instead of the actual viewstate
This is how the code looks like:
[Serializable]
public class MyOwnViewState
{
private Object _myViewStateField;
public Object MyViewStateProperty
{
get { return _myViewStateField; }
set { _myViewStateField = value; }
}
}
Notice the [Serializable] attribute.
Next we override the Loading and Saving of the viewstate.
protected override void LoadViewState(object savedState)
{
if (savedState != null)
{
object[] myState = (object[])savedState;
if (myState[0] != null)
base.LoadViewState(myState[0]);
if (myState[1] != null)
_myOwnViewState = (MyOwnViewState)myState[1];
}
}
First we check if the viewstate isn't null. Next we put the it in an object array. Finally we pull the custom object out of the object array and put it in a private field so we can use it.
Saving works in a similar way
protected override object SaveViewState()
{
object baseState = base.SaveViewState();
object[] allStates = new object[3];
allStates[0] = baseState;
allStates[1] = _myOwnViewState;
return allStates;
}
We save the state as a cumulative array of objects. And we add our custom object to the array.
The only thing that's left is use the custom object in the state machine
WizardFlowControl wizardFlowControl =
new WizardFlowControl(_wizardControl, _myOwnViewState);
wizardFlowControl.Handle();
That's it. Greetz, G
Labels: ASP.NET 2.0
0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home