3

In a webpage, I am storing a Dictionary in the ViewState :

Dictionary<string, string> items = new Dictionary<string, string>();
ViewState["items"] = items;

It works great. However, for some reasons, I want to use my own class instead of using Dictionary directly :

class MyDictionary : Dictionary<string, string> 
{
   ... 
}
MyDictionary items = new MyDictionary();
ViewState["items"] = items;

It doesn't work as expected. ASP.NET complains about the fact

MyDictionary is not marked serializable

It's ok since class attributes are not herited. So I changed my code :

[Serializable]
class MyDictionary : Dictionary<string, string> { ... }

But if I do so, I get another error message, this time after page postback :

The state information is invalid for this page and might be corrupted.
System.Web.UI.ObjectStateFormatter.Deserialize(Stream inputStream)

If viewstate can serialize a Dictionary, why it doesn't work for a class that inherit from it ? How to make this work?

tigrou
  • 4,236
  • 5
  • 33
  • 59
  • Are you adding controls dynamically, or anything like that, on the page? http://stackoverflow.com/questions/8946374/the-state-information-is-invalid-for-this-page-and-might-be-corrupted-only-in Your custom dictionary is fine, it should be in the ViewState without issues. – Jason Evans Aug 29 '12 at 09:22

1 Answers1

4

You need to a deserialization constructor to your class.

class MyDictionary : Dictionary<string, string> 
{
   public MyDictionary (){ }
   protected MyDictionary (SerializationInfo info, 
                           StreamingContext ctx) : base(info, ctx) { }
}

If you look inside a dictionary class, it requires this to deserialize.

protected Dictionary(SerializationInfo info, StreamingContext context);

Tried it with a test page and it works fine.

nunespascal
  • 17,584
  • 2
  • 43
  • 46