ASP.Net helps maintain state info in
different ways by keeping it on the page or on the local machine. It reduces
the usage of server resources because the info is kept on the local machine,
because no information is maintained on server side between trips.
Viewstate is one of the Client-Based State Management Options
In Viewstate a dictionary object is used
to keep the values between multiple requests of the page. Viewstate is the
default method to preserve page between round trips. The current state of page
and its controls is kept(hashed) in a string in the page in hidden field or in
the multiple hidden fields if the value is more than the
MaxPageStateFieldLength of the hidden field.
The page parses the string at page
initialization and restores the page info after the page is posted back to the
server.
For example if we enter a text into a textbox a refresh the page the textbox will be empty because the page is recreated.
Viewstate allows the text to repapulate after each postback, which makes sure that form is not cleared after the ok button is clicked. Viewstate can't arry values between pages but keeps it
unto page only.(see the image below)
Now if you run the project and enter your name in textbox and press ok button the name will be saved in viewstate and also assigned to label, if you press the refresh button it does nothing but postback to the server or refreshes the page.
After you press the refresh button you will notice the label still shows the name but textbox is empty, if you press the ok button again with textbox empty you will notice that label still shows the name its because of viewstate.
Viewstate is good unto page lavel but if you wish to transfer data between pages session or cookie might be used.
State management is an art which retains user specific
info between requests but most of the time the scope of info is global to
entire app, To achieve the goal of state management in the app you may mix up
the following client side state management options
- Control state
- Hidden fields