Powered by Blogger.

Thursday, March 13, 2014

How to store custom objects in view state in asp.net?

In this post we will discuss how we can store custom objects in view state in asp.net.

You can also check my previous posts on:

- asp.net mvc 4 tutorial

- Bind gridview using datareader in asp.net

- Generate WCF Proxy using SvcUtil.exe

To store an object in view state, the object must be serializable means, ASP.NET must be able to convert it into a stream of bytes so that it can be added to the hidden input field in the page. This process is known as serialization.

To make your objects serializable, you need to add a Serializable attribute before your class declaration.

public class Employee
private string firstName;
private string lastName;

public string FirstName
get { return firstName; }
set { firstName = value; }

public string LastName
get { return lastName; }
set { lastName = value; }
public Employee(string firstName, string lastName)
FirstName = firstName;
LastName = lastName;

Here the above class becomes a serializabled class, since we write the [Serializable] attribute in the beginning of the class.

Employee objEmployee = new Employee("Bijay", "Kumar");
ViewState["NewEmployee"] = objEmployee;

Here the Employee object will be stored in the view state.

To retrive the custom object from the view state write like below:

Employee  obj = (Employee)ViewState["NewEmployee"];

Remember If the Serializable attribute isn’t present, the class isn’t serializable, and you won’t be able to place instances of it in view state.