Follow in Twitter & Facebook

Like in Facebook

Powered By Blogger Widgets

Free Download

FREE Tools

Friday, August 3, 2012

ViewState example Asp.Net

In this article we will discuss about view state which is a popular statemanagement technique. Also you can check an article on Difference between cookie and session in

View state is a common technique to store information that’s used for multiple postbacks in a single web page. View state uses a hidden field that ASP.NET automatically inserts in the final, rendered HTML of a web page.

To store values in viewstate:

ViewState["Counter"] = 1;

To retrieve values from view state:

Int viewstateValue = (int)this.ViewState["Counter"];

But it is always good to check wether the view state value is null before trying to retrieve it like below:

if (ViewState["Counter"] == null)
//Handle the null value
viewstateValue = (int)ViewState["Counter"] + 1;

if you will not check for null, then if the view state contains null, it will through an null reference exception.

View state value is readable and is a converted Base64 string which can be tampered. But we can encrypt that in page level as well as project level.

To encrypt in Page level we have to add ViewStateEncryptionMode="Always" in Page directive.

Also we can made changes in web.config like below:

<pages viewStateEncryptionMode="Always" />

Also apart from integer or string types we can store our custom objects. But the custom object should be serializable.

Here is an example:
public class Customer
private string firstName;
public string FirstName
get { return firstName; }
set { firstName = value; }

public Customer(string firstName, string lastName)
FirstName = firstName;

Customer customer = new Customer("SharePointDotNet");
ViewState["CustomerDetails"] = customer ;

To retrive the custom object :
// Retrieve a customer from view state.
Customer customerRetrive = (Customer)ViewState["CustomerDetails"];

Typecast is very much necessary.

You can also check some SQL Server articles like: Joins in SQL Server 2008 and Delete and Truncate in sql server 2008 .

0 on: "ViewState example Asp.Net"