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

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

You can also check my previous posts on

global.asax file in Asp.Net,

switch statement in C#.Net

Some Optimization Tips in sql server.

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.

[Serializable]
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 retrieve the custom object from the view state writes 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.


You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →

Leave a Reply