title: Storing Dictionary<string, string> in ASP.NET view state?
body: <p>I'm trying to store a <code>Dictionary&lt;string, string&gt;</code> in the ViewState of a custom control I'm developing for ASP.NET 2.0:</p>
  
  <pre><code>private Dictionary&lt;String, String&gt; Items
      {
          get
          {
              object d = ViewState["Items"];
              return (d == null ? null : (Dictionary&lt;String, String&gt;)d);
          }
          set
          {
              ViewState["Items"] = value;
          }
      }
  </code></pre>
  
  <p>Accessing it looks like this:</p>
  
  <pre><code>public void UpdateData
  {
      if (this.Items == null)
          this.Items = new Dictionary&lt;string, string&gt;();
      else
          this.Items.Clear();
      //Fill the collection
  }
  </code></pre>
  
  <p>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 <code>null</code> out of the ViewState in the property <code>get</code>.</p>
  
  <p>I've done some research and have <a href="http://msdn.microsoft.com/en-us/library/ms178652%28VS.85%29.aspx" rel="noreferrer">found</a> that classes must implement <code>IStateManager</code> to be saveable in ViewState, and the <a href="http://msdn.microsoft.com/en-us/library/xfhwa508%28v=VS.80%29.aspx" rel="noreferrer">Dictionary MSDN page</a> appears to indicate that <code>Dictionary&lt;TKey, TValue&gt;</code> does not.  But I've stored dictionaries before in ViewState without a problem.  What's going on here?  Was my previous experience a fluke?</p>
  
  <p>UPDATE: I tried adding some test code to the property: <code>ViewState["ItemTest"] = "foo";</code> in the <code>set</code> and <code>string test = (string)ViewState["ItemTest"];</code> in the <code>get</code>.  Like the <code>Dictionary</code>, it comes out null.  So it doesn't appear to be a problem with the <code>Dictionary</code> being serializable.  Also, to clarify, <code>UpdateData</code> is called from my <code>RenderControl</code> override, which happens after <code>Page_Load</code> in the page that contains the control. </p>