I’m trying to store a Dictionary<string, string> in the ViewState of a custom control I’m developing for ASP.NET 2.0:
private Dictionary<String, String> Items
{
get
{
object d = ViewState["Items"];
return (d == null ? null : (Dictionary<String, String>)d);
}
set
{
ViewState["Items"] = value;
}
}
Accessing it looks like this:
public void UpdateData
{
if (this.Items == null)
this.Items = new Dictionary<string, string>();
else
this.Items.Clear();
//Fill the collection
}
When it gets set the first time the page loads, it appears to work fine. But on subsequent postbacks, the value returned is always null (the first condition always happens). Debugging shows that it’s getting null out of the ViewState in the property get.
I’ve done some research and have found that classes must implement IStateManager to be saveable in ViewState, and the Dictionary MSDN page appears to indicate that Dictionary<TKey, TValue> does not. But I’ve stored dictionaries before in ViewState without a problem. What’s going on here? Was my previous experience a fluke?
UPDATE: I tried adding some test code to the property: ViewState["ItemTest"] = "foo"; in the set and string test = (string)ViewState["ItemTest"]; in the get. Like the Dictionary, it comes out null. So it doesn’t appear to be a problem with the Dictionary being serializable. Also, to clarify, UpdateData is called from my RenderControl override, which happens after Page_Load in the page that contains the control.
You can store the dictionary in ViewState, but you are attempting to do this too late in the page life cycle. Just as ViewState is loaded after
Init, ViewState is saved before controls are rendered. Move your logic out ofRenderControland into another method or event handler earlier in the life cycle, such asPreRender.You will notice the that object is no longer null on subsequent postbacks as long as ViewState is not being disabled on either the control or its parent.