Understanding view State in Asp.net

Source: Internet
Author: User

What is viewstate?
We have many misunderstandings about viewstate. Viewstate does not save the control, but stores the value of the corresponding ID control in the form, especially the values of those controls that will be lost when the page is returned because they are not post with the form. Viewstate is generally not used to save sessions or transmit data between pages. After page return, viewstate cannot be used to dynamically create page controls. It does not reply to the control value after the page is returned. Even if the viewstate of a control is disabled, the value of the control will not be lost after the page is returned, such as the textbox and dropdownlist controls. What is viewstate?Viewstate stores the status of the last page processed on the server. It cannot save the values of those dynamically changed controls.

How does viewstate work?
All server-side controls have a viewstate attribute. If it is enable, The viewstate of this control will take effect. Where is the viewstate and how is it stored? When a page is loaded for the first time, all controls are serialized to viewstate and saved in a hidden form field named _ viewstate. This hidden field corresponds to the viewstate object on the server. The viewstate of the page uses the system. Web. UI. statebag object to store key-value pairs. When a callback occurs, the page deserializes viewstate and restores all controls. The viewstate of the control is stored as name-value in Base 64 encoding format on the page. When a page is reloaded, two methods related to viewstate are called, loadviewstate and saveviewstate. Below is a hidden field of _ viewstate on one of my pages.

<Input type = "hidden" name = "_ viewstate" value = "dnrato45tm5qzq7oz8ablwpxpje9mml0aq765qncmp2tq ="/>

Enable and disable viewstate
By default, the viewstate of all server controls is enabled and disabled in several ways.
1. Page Level
2. control level
3. Application Level
4. machine level
The page-level prohibit method is to write data at the beginning of the page.

<% @ Page enableviewstate = "false" %>
Or
<% @ Page enableviewstate = "true" %>

Control level is

<Asp: textbox id = "txtcode" runat = "server" enableviewstate = "false"/>
Or
<Asp: textbox id = "txtcode" runat = "server" enableviewstate = "true"/>

The program level is in Web. config.

<Pages enableviewstate = "false"/>
Or
<Pages enableviewstate = "true"/>

The machine level is in machine. config.

<Pages enableviewstate = "true" enableviewstatemac = "true".../>
Or
<Pages enableviewstate = "false".../>

Save and retrieve values in viewstate
Viewstate can process the following types
Basic type, basic type array, arraylist and hashtable, any object that can be serialized.

Run the following code to save the arraylist to viewstate and retrieve it:

Arraylist OBJ = new arraylist ();
// Some code
Viewstate ["viewstateobject"] = OBJ;
OBJ = viewstate ["viewstateobject"];

Performance problems
For better page rendering performance, viewstate should be as small as possible. Remember that the data in viewstate occupies a lot of network bandwidth. Therefore, we must use viewstate with caution. If the page and control do not need to be returned, you must disable the viewstate attribute. In general, viewstate stored outside the ASPX page will achieve better performance. To achieve this, we can use the savepagestatetopersistencemedium and loadpagestatefrompersistencemedium methods. In web. config or machine. config, disable viewstate on all or all pages of a program.

Note that viewstate can be stored only when the control is included in <form runat = Server>. However, even if all viewstates on the page are disabled, the page still stores 20 bytes of data in the viewstate, which is used to allocate data in the viewstate to the corresponding control during callback. Therefore, when the page does not return data at all, removing runat = "server" can reduce data by 20 bytes. If there are many such pages, 20-byte savings can also reduce the bandwidth to a certain extent. Viewstate should be used when necessary. Avoid using viewstate in controls such as DataGrid and datarepeater because viewstate occupies a large amount of data.

Below I provide a simple method for calculating the page viewstate size. Create a masterpagebase class, and all other pages must inherit it.

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 Questions
Two measures can be taken to prevent the viewstate from being counterfeited.
Enableviewstatemac attribute
Encrypt the content in viewstate
Enableviewstatemac performs a machine authorization authentication (MAC), which should be used at the page level or program level. When this attribute is set, a hash value of viewstate is appended before viewstate is rendered. When a callback occurs, the hash value is re-calculated and checked. If they do not match, the page will reject the display, so that the viewstate is not modified by the listener.

Set encryption for viewstate content in machine. config

<Machinekey validation = "3DES"/> or <machinekey validation = "sha1"/>

Where viewstate is prone to errors
When a page control is transmitted to another page (the second page), an error occurs. The solution is to disable viewstate on the second page.

 

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.