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.
- ViewState["Counter"]=count;
For retrieving data from ViewState we need to type cast it using type cast operator.
- 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.
- public class Details
- {
-
- public int Id
- {
- get;
- set;
- }
- public string Name
- {
- get;
- set;
- }
- public string City
- {
- get;
- set;
- }
-
- public List < Details > GetDetails()
- {
-
- List < Details > Persons = new List < Details > ();
- Persons.Add(new Details
- {
- Id = 1, Name = "Rajeev", City = "Bangalore"
- });
- Persons.Add(new Details
- {
- Id = 2, Name = "Raj Kumar", City = "Chennai"
- });
- Persons.Add(new Details
- {
- Id = 3, Name = "Raj", City = "Mumbai"
- });
- Persons.Add(new Details
- {
- Id = 4, Name = "Shiva", City = "Pune"
- });
- Persons.Add(new Details
- {
- Id = 5, Name = "Lalit", City = "Ahmedabad"
- });
- return Persons;
-
- }
-
- }
- Details d = new Details();
- ViewState["Data"] = d.GetDetails();
This will end up in getting error. To solve this issue add Fertilizable attribute to class definition.
- [Serializable()]
- public class Details
- {
- }