Friday, October 13, 2006

[ASP.NET] Serializing/Deserializing Passing Objects Across Pages with LosFormatter

On our ordinary basis, we pass the values or object values across two pages using Session, Form Posting, PreviousPage reference in ASP.NET. But however, we could not able to append the object to the query string (unless you use the Session state instead). There is another alternative way - passing the serialized the object values into string presentation in query string.

How ?? First of all, are you familiar with this ?

< input type="hidden" name="__VIEWSTATE" value="dDwxMzIwMTI1MjYwO3Q8O2w8aTwxPjs+O2w8dDw7bDx
5B1K2D7xw==" / >

If you do, that's good. It is ViewState, the hidden field that stores control state, which the state values (eg. object values, primitive type values) are serialized and deserialized into base-64 string using LosFormatter. Similarly, this approach can be used to serialize the object and pass it to the next page in query string.

The following example shows you how to pass the serialized ArrayList to the next page using LosFormatter.



private void Page_Load(Object sender, EventArgs e)
ArrayList ary = new ArrayList();

System.Web.UI.LosFormatter formatter = new System.Web.UI.LosFormatter();
StringWriter writer = new StringWriter();

HyperLink1.NavigateUrl = "secondpage.aspx?value=" + writer.ToString();

Check the URL in the HyperLink control in Firstpage.aspx, it would be something like


The ArrayList object has just been serialized ! How to deserialize the object back?



private void Page_Load(Object sender, EventArgs e)
System.Web.UI.LosFormatter formatter = new System.Web.UI.LosFormatter();
ArrayList aryL = (ArrayList)formatter.Deserialize(Request.QueryString["value"]);


* Be noted, you need to explicitly specify the System.Web.UI.LosFormatter in the object instantiation. You will get the undefined Serialize()/Deserialize() method, otherwise. Watch out the number of characters supported in the URL. Not all objects are suitable to be serialized, only relatively small-size objects are appropriate to do so.

The LosFormatter class is extremely useful especially you override the SaveViewState() or LoadViewState() of the Page class/ Control, you need this class to do the serialization or deserialization of control states.

1 comment:

Herson alvarado said...

Thanks its works for me from colombia :)