Asp.Net uses View State to track the values in the Controls. We can add custom values to the View State also.
The ViewState in asp.net provides a dictionary object for retaining values between multiple requests for the same page.
This is the default method that the page uses to preserve page and control property values between round trips.
ASP.Net stores view state on client side in hidden field __ViewState in encrypted form.
When a page is created on web server this hidden control is populate with state of the controls and when page is posted back to server this information is retrieved and assigned to controls.
We can look at this field by looking at the source of the page i.e. by right clicking on page and selecting view source option. We do not need to worry about this as this is automatically handled by ASP.Net.
We can use view state to store our own page-specific values across round trips when the page posts back to itself.
if your application is maintaining user-specific information — that is, information that is used in the page but is not necessarily part of any control — we can store it in view state.
Syntax to add Value in View State Object:
ViewState[”myviewstate”] = “Hello World”;
ViewState.Add (“myviewstate”, “Hello World”);
Syntax to Read values from ViewState Object:
String strValue = ViewState[”myviewstate”].ToString();
Advantages of using view state :-
No server resources are required: The view state is contained in a structure within the page code.
Simple implementation: View state does not require any custom programming to use. It is on by default to maintain state data on controls.
Enhanced security features: The values in view state are hashed, compressed, and encoded for Unicode implementations, which provides more security than using hidden fields.
Disadvantages of using view state are:
Because the view state is stored in the page itself, storing large values can cause the page to slow down when users display it and when they post it. This is especially relevant for mobile devices, where bandwidth is often a limitation.
Mobile devices might not have the memory capacity to store a large amount of view-state data.
Potential security risks:
The view state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can still be tampered with. The information in the hidden field can be seen if the page output source is viewed directly, creating a potential security issue.