Solve ViewState Serialization Error

As we know Http is a stateless protocol. State is not maintained between various request to the server. ASP.NET provides two types of state management techniques namely: Client Side, Server Side. ViewState is one of the client Side State management. It is used to store the state of page between postbacks. ASP.NET controls uses this property to maintain state between various postbacks. ViewState is stored as hidden fields in page.

If you want to add a variable to the View State then we will use the following code.

  1. ViewState["Counter"]=count;   
For retrieving data from ViewState we need to type cast it using type cast operator.
  1. string count=(string)ViewState["Counter"];   
ViewSate can be used to store any data type. For storing and retrieving primitive data type there is no problem. But when we want to store User Defined data types then we may end up in getting the error:

"class must be marked as Serializable or have TypeConvertor other than ReferenceConvertor to be put in ViewSate." or "PublicKeyToken=null' is not marked as serializable."

This is because our class is not Serializable . So an object of this type can’t be stored into ViewState.
  1. public class Details   
  2. {  
  3.   
  4.     public int Id   
  5.     {  
  6.         get;  
  7.         set;  
  8.     }  
  9.     public string Name   
  10.     {  
  11.         get;  
  12.         set;  
  13.     }  
  14.     public string City   
  15.     {  
  16.         get;  
  17.         set;  
  18.     }  
  19.   
  20.     public List < Details > GetDetails()   
  21.     {  
  22.   
  23.         List < Details > Persons = new List < Details > ();  
  24.         Persons.Add(new Details   
  25.         {  
  26.             Id = 1, Name = "Rajeev", City = "Bangalore"  
  27.         });  
  28.         Persons.Add(new Details   
  29.         {  
  30.             Id = 2, Name = "Raj Kumar", City = "Chennai"  
  31.         });  
  32.         Persons.Add(new Details   
  33.         {  
  34.             Id = 3, Name = "Raj", City = "Mumbai"  
  35.         });  
  36.         Persons.Add(new Details   
  37.         {  
  38.             Id = 4, Name = "Shiva", City = "Pune"  
  39.         });  
  40.         Persons.Add(new Details   
  41.         {  
  42.             Id = 5, Name = "Lalit", City = "Ahmedabad"  
  43.         });  
  44.         return Persons;  
  45.   
  46.     }  
  47.   
  48. }  
  1. Details d = new Details();   
  2. ViewState["Data"] = d.GetDetails();   
This will end up in getting error. To solve this issue add Fertilizable attribute to class definition.
  1. [Serializable()]   
  2. public class Details   
  3. {   
  4. }