4

I have a class like this that I want to save in ViewState for an asp.net UserControl. It basically extends a generic list with a few methods but also adds some properties, e.g.

public class MyListClass: List<MyObject>
{
    public string ExtraData;
 // some public methods
}

MyObject is serializable, with methods implemented like this:

[Serializable()]
class MyObject 
{
    public MyObject(SerializationInfo info, StreamingContext ctxt)
    {
        Prop1 = (string)info.GetValue("Prop1", typeof(string));
        //...
    }
    public void GetObjectData(SerializationInfo info, StreamingContext ctxt)
    {
        info.AddValue("Prop1",Prop1);
    }
}

And generic lists are inherently serializable. ViewState works fine with List<MyObject> but I can't seem to figure out how to implement serialization for MyListClass.

Intuitively what I want to do is something like this:

public MyListClass(SerializationInfo info, StreamingContext ctxt)
{
    ExtraData= (string)info.GetValue("ExtraData", typeof(string));
    this = (List<MyClass>)info.GetValues("BaseList",typeof(List<MyClass>));
}

Obviously that won't work. What is the right way to do this?

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jamie Treworgy
  • 23,934
  • 8
  • 76
  • 119

2 Answers2

3

You should just be able to put the Serializable tag on MyListClass, which will cause ExtraData to be serialized as its own field.

KeithS
  • 70,210
  • 21
  • 112
  • 164
  • I get "The state information is invalid for this page and might be corrupted" when trying to restore ViewState. – Jamie Treworgy Dec 21 '10 at 22:23
  • Hmm... it seems that I had tinkered with something else while I was experimenting here is the problem. Damn. Sho 'nuf, that is all I needed to do. Though if I needed to customize the serialization process I am still not sure how I'd do it, luckily I don't need to for this object. – Jamie Treworgy Dec 21 '10 at 22:51
  • If you need to customize the serialization process, say if ExtraStuff needed to contain any cruft that couldn't be serialized as its field (happens), you need to implement either the IDeserializationCallback interface (to provide custom post-deserialization behavior), or ISerializable (which allows almost complete control over what goes where). IDSCallback is the easier, and is very useful for doing things like hooking up event handlers and other external references your object may have that don't serialize. – KeithS Dec 21 '10 at 23:12
0

See the documentation on the PageStatePersister Class, which is how ASP.NET handles ViewState these days. In particular, see the ObjectStateFormatter Class, which is the default implementation of the IStateFormatter interface.

From that documentation, it appears that any class that can be serialized using the BinaryFormatter should work.

John Saunders
  • 160,644
  • 26
  • 247
  • 397