views:

112

answers:

2

Hi,

I have one XML document which I want to store it inside ViewState so on each post back I do not need to load it from its physical path again. I do not want to store it in SessionState as well.

when I tried to srote it in ViewState I get an error:

Exception Details: System.Runtime.Serialization.SerializationException: Type 'System.Xml.XmlDocument' in Assembly 'System.Xml, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.

my property is something like this:

private XmlDocument MyDocument      {
     get
     {
      object viwObj = ViewState["MyDocument"];
      if (viwObj != null)
       return (XmlDocument)viwObj;

      XmlDocument xmlDoc =  GetMyDocument();
      ViewState["MyDocument"] = xmlDoc;

      return xmlDoc;
     }
    }

How can I make an xml document serializable then?

thanks

A: 

You could always just convert your XML document to it's string representation and save/load that into viewstate. I hope this is a relatively small document?

Paddy
+3  A: 

You could serialize your XmlDocument to an XML string and save that string in the ViewState.

Serialization:

using (var sw = new StringWriter())
using (var xw = new XmlTextWriter(sw))
{
    xmlDoc.WriteTo(xw);
}

ViewState["MyDocument"] = sw.ToString()

Deserialization:

var xmlDoc = new XmlDocument();
xmlDoc.LoadXml((string) ViewState["MyDocument"]);

This sort of serialization does not really fit into a get/set property, so you will most likely want to override the SaveViewState() and LoadViewState() methods of your user control/page, and add the serialization/deserialization logic within these.

Jørn Schou-Rode
Thanks! It was really really useful information Jørn Schou-Rode!
burak ozdogan