IntroductionHi Guys, when we are work with custom object in Viewstate in ASP.NET page, this error will be occured. Error Codeusing System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
public class CustomObject
{
public CustomObject(string name, string address)
{
this.name = name;
this.address = address;
}
string name;
public string Name
{
get { return name; }
set { name = value; }
}
string address;
public string Address
{
get { return address; }
set { address = value; }
}
}
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
List<CustomObject> collections = new List<CustomObject>();
collections.Add(new CustomObject("Ravee", "Singapore"));
collections.Add(new CustomObject("David", "Japan"));
ViewState["CustomObject"] = collections;
}
}
private void AccessObjectFromVS()
{
if (ViewState["CustomObject"] != null)
{
List<CustomObject> collections = (List<CustomObject>)ViewState["CustomObject"];
// bind to grid or whatever object, then page will throw error as like above
}
}
}
The ReasonsWhen we are access the viewstate with custom object in ASP.NET its every page will validate the ViewState and then its process, so as per error message,when it try to validate it will de-serialize the viewstate., but Custom object not mark as serialize.due to this reason ASP.NET State engine throw this error. The ResolutionsJust mark your custom object as serialize. [Serializable]
public class CustomObject
{
public CustomObject(string name, string address)
{
this.name = name;
this.address = address;
}
string name;
public string Name
{
get { return name; }
set { name = value; }
}
string address;
public string Address
{
get { return address; }
set { address = value; }
}
}Just class header attribue, we have added serializable.that's this is save your time and finding. |