| |
|
How to store values between postbacks in ASP.NET? What is viewstate in ASP.NET?
The postback question is the heart of any interview on ASP NET. When a postback happens (i.e. when a form is submitted to a server), the variable values
that are set in the code-behind page are erased from the memory of the client system.
This concept would be different from what happens in Windows-based applications, where
the variable variables persist in memory until they are freed from the memory either by the
garbage collector, or by specific codes like dispose or finalize.
In web applications, variable values simply get erased. But it is very simple to persist
these values. They may be persisted using the Viewstate object.
Before the postback is invoked, the variable's value is saved in a viewstate object. In the
recieving page, the viewstate's value may be retrieved back. See example code below...
//Save the value in ViewState object before the PostBack
ViewState("SomeVar") = txtFirstName.text;
//Retrieve the value from ViewState object after the PostBack
String strFirstName = ViewState("SomeVar").ToString();
Note that the viewstate value is saved and then passed to the next page by ASP.NET in the form
of a hidden variable. Ideally, big values like datasets should not be saved in viewstate as they may tend
to slow down the performance of the web page.
Apart from the viewstate object, values may also be sent across postbacks between pages using
Application, Session and Cache objects.
Page Redirection
Values Between Pages
Worker Process
Page Life Cycle
Global Variables
Postback
Server Control
Viewstate
Send Email
Namespace
Localization
Event Handler
Validation
Global.asax
HttpHandler
Session
Cookie
EnableViewState
Smart Navigation
Web Farm
Dataset
Register
| |