I’ve got a custom UserControl I’m working with which hosts dynamically created controls and I’m running into an odd situation where I’m seemingly losing ViewState information. In my overridden SaveViewState method on the base.SaveViewState() call, I would expect it to return me back an object containing everything that was in ViewState, but it is instead returning null.
protected override object SaveViewState()
{
object[] tempState = new object[2];
tempState[0] = base.SaveViewState(); //***suspected issue here, tempState[0] == null -- why?
//? this.ViewState["CompanyID"] returns me the guid I'm expecting
//... code instantiating and populating lstDataControlInfos
tempState[1] = lstDataControlInfos;
return tempState;
}
I put a breakpoint in that method, and I can use the immediate window to query ViewState[“CompanyID”] and verify that there is indeed a CompanyID stored in ViewState. Maybe I’m misunderstanding something about ViewState, but shouldn’t that call be returning what is already in ViewState (including my CompanyID)? The issue becomes a problem on postback in the overridden LoadViewState method, as I no longer have any way to get CompanyID out of ViewState; it comes back null.
protected override void LoadViewState(object savedState)
{
object[] tempState = (object[])savedState;
//tempState[0] == null, as it was stored in the previous SaveViewState call
//any reference to ViewState["CompanyID"] comes back null
base.LoadViewState(tempState[0]);
}
I mentioned I’ve got dynamic controls I’m serializing to and deserializing from ViewState inside this control, and those all seem to be working properly. What would cause base.SaveViewState() to return null when I know for a fact and can verify (via immediate window) there is data in ViewState during the SaveViewState call?
When you save values to ViewState, the value is marked as dirty if ViewState is being tracked.
Tracking starts in TrackViewState, which is after Initialize and before Load.
Tracking ends in SaveViewState, which is after PreRender.
If ViewState isn’t being tracked when a value is set in ViewState, it won’t be persisted when you call SaveViewState. This is a good thing: it means you can use ViewState during the Init phase without bloating the serialized ViewState.
When you dynamically add controls to the tree, you should note that:
Values set before you add the control to the control tree will not be persisted, even if you add the control while ViewState is being tracked.
Values set after you add the control to the control tree will be persisted, if you are in a phase where ViewState is being tracked.
At what point in the page lifecycle are you setting ViewState[“CompanyID”], and are you doing so before or after you add your control to the control tree?