Reprinted viewstate (1) things that are too classic have to be reprinted and saved

Source: Internet
Author: User
Asp.net viewstate

Viewstate is used to maintain the UI status of the page.
Viewstate is a mechanism that ASP. NET uses to track the status values of server controls. Otherwise, these values are not returned as part of the HTTP form. For example, the text displayed by the label control is saved in viewstate by default. As a developer, You can bind data or set the label only once when loading the page for the first time. In the subsequent return, the label text will be automatically refilled from viewstate. Therefore, in addition to reducing tedious work and code, viewstate can also reduce the number of database round trips.

Viewstate is a hidden form field managed by the ASP. NET page framework. When ASP. when a page is executed, the viewstate value and all controls on the page are collected and formatted into an encoding string, the Value Attribute (<input type = hidden>) of the hidden form field is assigned ). Because the hidden form field is a part of the page sent to the client, the viewstate value is temporarily stored in the browser of the client. If the client chooses to return the page to the server, the viewstate string will also be returned. In Figure 2 above, we can see the viewstate form field and its return value. After the callback, the ASP. NET page framework parses the viewstate string and fills in the viewstate attribute for the page and each control. Then, the control uses the viewstate data to restore itself to the previous state. There are three other minor issues worth noting about viewstate.
  • To use viewstate, you must have a server form tag (<form runat = Server>) on the ASPX page ). Form fields are required so that hidden fields containing viewstate information can be returned to the server. In addition, this form must also be a form on the server. When the server executes this page, the ASP. NET page framework can add hidden fields.
  • The page itself stores about 20 bytes of information in viewstate, which is used to distribute the PostBack data and viewstate values to the correct control during back-to-transmission. Therefore, even if viewstate is disabled for the page or application, you can still see a small number of remaining bytes in viewstate.
  • If the page is not returned, you can omit the <form> flag on the server to remove the viewstate from the page.
Select session status or viewstate? In some cases, it is not the best choice to save the state value in viewstate. The most common alternative is session state, which is generally applicable:
  • A large amount of data. Viewstate increases the size of the page (HTML payload) sent to the browser and the size of the returned form. Therefore, viewstate is not suitable for storing a large amount of data.
  • Security data not displayed in the UI. Although viewstate data has been encoded and can be encrypted, it is the most secure to never send data to the client. Therefore, session is a safer choice. (Because the database requires additional creden。 for verification, it is safer to store data in the database. You can add SSL to obtain a safer link .) However, if the private data is displayed in the UI, You should have confirmed the link security. In this case, placing the same value in viewstate does not reduce security.
  • Objects not serialized to viewstate, such as dataset. The viewstate serialization program is optimized only for a small part of common object types, as shown below. Other serializable types may be retained in viewstate, but the speed slows down and generates a very large viewstate.
When viewstate is used to obtain the optimal performance, every object must be first serialized to viewstate and then deserialized through callback. Therefore, viewstate is not a cost-effective method. However, if you follow some simple principles to control the viewstate cost, it usually does not have a significant performance impact.
  • Disable viewstate if not required. This issue is described in the "reduce the use of viewstate" section below.
  • Use the optimized viewstate serialization program. The types listed above have special serialization programs, which are fast to run and have been optimized to generate a small viewstate. To serialize a type not listed above, you can create a custom typeconverter to significantly improve its performance.
  • Minimize the number of objects in viewstate. For example, do not use a two-dimensional string array (name/value, the number of objects is the same as the length of the array), but use two string arrays (only two objects ). However, before the two known types are stored in viewstate, the conversion between the two types does not get any performance improvement, because this is actually equivalent to two conversions.
By default, viewstate is enabled when viewstate is used, and the content stored in viewstate is determined by each control (rather than by PAGE developers. Sometimes, this information is useless to applications. Although there is no harm, it will significantly increase the size of the page sent to the browser. Therefore, if you do not need to use viewstate, you 'd better disable it, especially when the viewstate is large. You can disable viewstate based on each control, page, or application. Viewstate is no longer required in the following cases: Page
  • The page is not returned to itself.
Widget
  • It is not a control event.
  • Controls do not have dynamic or data-bound property values (or they are set in code for each request ).
The DataGrid Control is a heavyweight user of viewstate. By default, all the data displayed in the grid is stored in viewstate. This is useful when complicated operations (such as complex searches) are required to obtain data. However, this behavior of the DataGrid sometimes makes the viewstate cumbersome.

For example, a simple page is in the above situation. Because the page is not returned to itself, it does not need viewstate.

When viewstate is enabled, this small grid will add an HTML payload of more than 3000 bytes to the page! Use ASP. NET tracing or view the source code of the page sent to the browser (as shown in the following code.

<% @ Page Language = "C #" %>
<% @ Import namespace = "system. Data" %>
<HTML>
<Head>
<Title> reduce the page's "HTML payload" </title>
</Head>
<Body>
<Form runat = "server">
<H3>
Disable viewstate to reduce the page's "HTML payload"
</H3>
<P>
<Asp: DataGrid id = "datagrid1" runat = "server" enableviewstate = "false"
Borderstyle = "NONE" borderwidth = "1px" bordercolor = "# cccccc"
Backcolor = "white" cellpadding = "5">
<Headerstyle font-bold = "true" forecolor = "white" backcolor = "#006699">
</Headerstyle>
</ASP: DataGrid>
</P>
</Form>
</Body>
</Html>
<SCRIPT runat = "server">
Void page_load (Object sender, eventargs e ){
Dataset DS = new dataset ();
DS. readxml (server. mappath ("testdata. xml "));

Datagrid1.datasource = Ds;
Datagrid1.databind ();
}
</SCRIPT>

Disable viewstate

 

In the preceding example, viewstate is disabled by setting the enableviewstate attribute of the mesh to false. Viewstate can be disabled for a single control, the entire page, or the entire application, as shown in the following figure: each control (on the tag): SP: DataGrid enableviewstate = "false "? /> Each page (in the Command): <% @ page enableviewstate = "false "? %>

Each application (in Web. config): <pages enableviewstate = "false "? />

Make viewstate safer because viewstate is not formatted as clear text, some people sometimes think it is encrypted, but it is not. On the contrary, viewstate only uses base64 encoding to ensure that the value does not change during the round-trip process, regardless of the response/Request Encoding used by the application. You can add two viewstate security levels to an application:
  • Tamper-proofing
  • Encryption
It should be noted that viewstate security has a direct impact on the time required to process and render ASP. NET pages. Simply put, the higher the security, the slower the speed. Therefore, if you do not need to add security protection against tampering with the viewstate, the hash code cannot ensure the security of the actual data in the viewstate field, however, it can significantly reduce the possibility that someone has cheated the application through viewstate, that is, to prevent returning the value that the application normally prohibits users from entering. You can set the enableviewstatemac attribute to instruct ASP. NET to append a hash code to the viewstate field:
<%@Page EnableViewStateMAC=true %>

Enableviewstatemac can be set at the page level or at the application level. During callback, ASP. NET generates a hash code for viewstate data and compares it with the hash code stored in the return value. If the hash code at the two locations does not match, the viewstate data will be discarded and the control will be restored to the original settings. By default, ASP. NET uses the sha1 algorithm to generate the viewstate hash code. In addition, you can set <machinekey> In the machine. config file to select the MD5 algorithm, as shown below:
<machineKey validation="MD5" />

Encryption

Encryption can be used to protect the actual data values in the viewstate field. First, enableviewstatmac = "true" must be set as described above ". Then, set the machinekey validation type to 3DES. This instructs ASP. NET to use the Triple DES symmetric encryption algorithm to encrypt the viewstate value.

<Machinekey validation = "3DES"/>

By default, ASP. NET creates a random authentication key and stores it in the local security authorization (LSA) of each server. To verify the viewstate field created on another server, the validationkey of the two servers must be set to the same value. If you want to use one of the preceding methods to set viewstate security for applications running in web domain configuration, you need to provide a unique and shared verification key for all servers. The verification key is a random string containing 20 to 64-bit cryptographic enhancement bytes, represented by 40 to 128 hexadecimal characters. The longer the key, the more secure it is. Therefore, we recommend that you use a 128-character key (if supported by a computer ). For example:
<machineKey validation="SHA1" validationKey="            F3690E7A3143C185AB1089616A8B4D81FD55DD7A69EEAA3B32A6AE813ECEECD28DEA66A            23BEE42193729BD48595EBAFE2C2E765BE77E006330BC3B1392D7C73F" />

The system. Security. cryptography namespace includes the rngcryptoserviceprovider class, which can be used to generate this string, as shown in the following generatecryptokey. aspx example:

<% @ Page Language = "C #" %> <% @ import namespace = "system. security. cryptography "%> <HTML> <body> <form runat =" server "> Summary ASP. Net viewstate is a new State service that allows developers to track the UI state based on each user. Viewstate is nothing mysterious. It just uses an old web programming technique: It transfers the State back and forth in a hidden form field and applies it directly to the page processing framework. But the results are very good-you only need to write and maintain a small amount of code in Web-based forms. Users may not always need it, but I think when you need it, you will find that viewstate is a lot of ASP provided to page developers. net is a very satisfactory new feature.

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.