Understanding the view state in ASP.net

Source: Internet
Author: User
Tags config hash httpcontext
asp.net

What is ViewState?
We have a lot of misunderstandings about viewstate. Instead of saving the control, ViewState saves the values of the corresponding ID controls in the form, especially those that are lost when the page is returned because they do not post with the form. ViewState are generally not used to save sessions or to transfer data between pages. After the page is returned, ViewState cannot be used to dynamically create the controls for the page. He does not reply to the value of the control after the page returns. Even the viewstate of a control is disabled, and the value of the control is not lost when the page is returned, such as a textbox,dropdownlist control. Then what is ViewState? ViewState saves the last page state that was processed on the server. He cannot save the values of controls that are dynamically changed.

How does the ViewState work?
All server-side controls have a ViewState attribute. If he is enable, the ViewState of this control will work. Where is the viewstate, and how is it stored? When a page loads for the first time, all controls are serialized to viewstate and stored in a hidden form field called _viewstate. This hidden field corresponds to the ViewState object on the server side. The ViewState of the page uses the System.Web.UI.StateBag object to store key-value pairs. When a postback occurs, the page deserializes viewstate and then restores all the controls. The ViewState for saving controls in the page is stored as name-value in the Base 64 encoding format. When a page is reloaded, two ViewState-related methods, LoadViewState and SaveViewState, are invoked. The following is a _viewstate hidden field in one of my pages.

<input type= "hidden" name= "__viewstate" value= "dnrato45tm5qzq7oz8ablwpxpje9mml0aq765qncmp2tq=="/>
Enable and disable ViewState
By default, the ViewState of all server controls is turned on, and there are several ways to disable it.
1. Page level
2. Control Level
3. Application level
4. Machine level
Page-level prohibitions are written at the beginning of the page

<%@ Page EnableViewState = "False"%>
Or
<%@ Page EnableViewState = "True"%>
The control level is

<asp:textbox id= "Txtcode" runat= "Server" enableviewstate= "false"/>
Or
<asp:textbox id= "Txtcode" runat= "Server" enableviewstate= "true"/>
Program level is in Web.config

<pages enableviewstate= "false"/>
Or
<pages enableviewstate= "true"/>
The machine level is in the Machine.config.

<pages enableviewstate= "true" enableviewstatemac= "true" .../>
Or
<pages enableviewstate= "false" .../>
Saving and fetching values in ViewState
ViewState can handle the following types
Basic types, array of base types, ArrayList and Hashtable, any object that can be serialized.

The following code is to save the ArrayList to the ViewState and remove

ArrayList obj = new ArrayList ();
Some Code
viewstate["viewstateobject"] = obj;
obj = viewstate["Viewstateobject"];
Performance issues
For better page rendering performance, the ViewState should be as small as possible. Remember that the data in the viewstate consumes a lot of network bandwidth. So we should use the viewstate carefully. If pages and controls do not need to be returned, the ViewState property is prohibited. Typically, saving viewstate outside of an ASPX page results in better performance. To achieve this, we can use both Savepagestatetopersistencemedium and LoadPageStateFromPersistenceMedium methods. In Web.config or Machine.config settings to prevent the viewstate of all pages or all program pages of a program.

Note that only controls are contained in <form runat=server> to store viewstate. However, even if all the viewstate of the page is blocked, the page still holds 20 bytes of data in the ViewState, which is used to assign the corresponding control to the data in the ViewState. So when the page doesn't return completely, removing runat= "server" can reduce 20 bytes of data. If there are many such pages, 20-byte savings can also reduce the bandwidth to some extent. The viewstate should be used when necessary. Avoid using ViewState in controls such as DataGrid and DataRepeater, because the viewstate of these controls is quite large.

Below I provide a simple way to calculate the size of the page viewstate. Create a Masterpagebase class, and then all other pages will inherit from him.

public class MasterPageBase:System.Web.UI.Page
... {
  protected override void OnPreRender (EventArgs e)
  ... {
    object viewstateobject = httpcontext.current.request["__viewstate"];
    if (viewstateobject = null)
      HttpContext.Current.Trace.Warn ("The ViewState Size is:", "0");
    Else
      HttpContext.Current.Trace.Warn ("The ViewState Size is : ",
        httpcontext.current.request[" __viewstate "]. Length.tostring ());
    Base. OnPreRender (e);
 }
}
Security issues
can take two measures to prevent ViewState from being phishing
Use the enableViewStateMac property
to encrypt content in ViewState
enableViewStateMac will perform a machine authorization verification (MAC), which should be used at the page level or at the program level. When set, this property appends a viewstate hash value to the ViewState rendering. When the postback occurs, the hash value is recalculated and checked. If they do not match, the page will reject the display, ensuring that the ViewState has not been tampered with.

Set up encryption of ViewState content in Machine.config

<machinekey validation= "3Des"/> or <machinekey validation= "SHA1"/>
ViewState error-prone places
When you transfer a page's control to another page (the second page), an error usually occurs. The workaround is to disable ViewState in the second page.




Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.