Can I store xmlDocument object in ViewState?
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["MyD开发者_Python百科ocument"];
if (viwObj != null)
return (XmlDocument)viwObj;
XmlDocument xmlDoc = GetMyDocument();
ViewState["MyDocument"] = xmlDoc;
return xmlDoc;
}
}
How can I make an xml document serializable then?
thanks
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.
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?
精彩评论