Tuesday, November 20, 2007

Viewstate in Asp.Net 2.0

Asp.Net 2.0 contain many new feature over 1.1, ASP.NETincludes a caching system that allows you to retain information without sacrificing server scalability. Each state management choice has a different lifetime, scope, performance overhead, and level of support.

Asp.Net 2.o View State

View state should be your first choice for storing information within the bounds of a single page.
View state is used natively by the ASP.NET web controls. It allows them to retain their properties between postbacks. You can add your own data to the view state collection using a built-in page property called ViewState. Like most types of state management in ASP.NET, view state relies on a dictionary collection, where each item is indexed with a unique string name.

For example, consider this code:

ViewState["Counter"] = 1;

It place value 1 into the ViewState collection. If there is currently no item with the name Counter, a new item will be added automatically. If there is already an item indexed under the name Counter, it will be replaced. When retrieving a value, you use the key name. You also need to cast the retrieved value to the appropriate data type. This extra step is required because the ViewState collection stores all items as generic objects, which allows it to handle many different data types. Here’s the code that retrieves the counter from view state and converts it to an integer:

int counter;
if (ViewState["Counter"] != null)
{
counter = (int)ViewState["Counter"];
}

No comments: