It is necessary to maintain state information for Web pages and their controls. However, since web applications are built on top of the HTTP protocol, which is a stateless protocol, maintaining state information becomes very difficult. In order to solve this problem, ASP.NET 2.0 technology provides a variety of solutions, such as using Session, Cookie, view state, control state, hidden fields, query strings, personalized user configuration (Profile), etc. For using ASP.NET 2.0 technology to create server controls, maintaining state information is also very important. The main solution is to use view state and control state. This article explains the basic knowledge of view state (ViewState) in detail, and introduces the application method of view state through typical applications.
View state overview
View state is a very important technology that allows the page and the controls in the page to maintain state information during the round trip from the server to the client and back from the client. In this way, a stateful and continuously executed page effect can be created on top of a stateless environment like the Web. This section mainly introduces the operating mechanism, application methods, stored data types, performance and security, view state blocking (this is a new feature of ASP.NET 2.0), advantages and disadvantages of view state.
(1)
The specific running process of the view state of the running mechanism is: whenever the user requests an .aspx page, the .NET framework first serializes the state data of the related controls into a string, and then makes it a file named __VIEWSTATE The Value value of the hidden field is sent to the client. If the page is requested for the first time, then the server control will also be executed for the first time. The hidden field named __VIEWSTATE only contains the default information of the control, which is usually empty or null. In the subsequent postback event, the property state of the server control available in the previous postback is saved in ViewState. This allows the server control to monitor the state before the currently handled postback event occurs. These processes are taken care of by the .NET framework, and for users, executing the .aspx page will have the effect of continuous execution.
(2) Stored data types
View state can store multiple types of data, and in order to improve operating efficiency, the view state itself also includes a set of optimized serialization methods for common types. The data types supported by the view state serialization method by default include the following: String, Int32, Unit, Color, Array, ArrayList, HashTable and custom type converter TypeConverter.
View state has been optimized for Array, ArrayList, and HashTable objects containing the types listed above. Therefore, when using view state in controls, you should try to limit your use to the simple data types above, as well as optimized types. Here, we need to focus on the custom type converter TypeConverter, which provides a unified method to convert the value type to other types and access standard values and sub-properties. For example, you can use TypeConverter to convert a string to a numeric value, or a numeric value to a string. If there is no type converter, the page framework will use the binary serialization function provided by the .NET framework to serialize the object. This process is very resource-consuming.
(3) Performance and Security
When using view state, objects must be serialized first and then deserialized via postback. So, we have to know something about ViewState performance. By default, the control's ViewState will be enabled. If you do not need to use ViewState, it is best to turn it off. ViewState will no longer be needed in the following situations: (1) The control does not define server-side events (the control events at this time are all client-side events and do not participate in postback); (2) The control has no dynamic or data-bound property values. The way to turn off the view state is to set the control's EnableViewState value to "false", that is, EnableViewState="false".
By default, when the content related to the view state is compiled and sent to the client, the reader will see the __VIEWSTATE hidden field content in the HTML code of the page. These are some meaningless strings and are the result of the .NET framework encoding the relevant content through Base64 encoding. They are sent back and forth between the client and server in clear text. In some cases, such as when sensitive content such as passwords, accounts, connection strings, etc. are involved, it is very unsafe to use the default method. To this end, the .NET framework provides two security mechanisms for ViewState:
Verification mechanism:
You can instruct the .NET framework to append a hash code to the ViewState data by setting the EnableViewStateMAC="true" attribute (the hash code is a A SHA1 type with a length of 160 bits, so it will seriously affect execution performance). When a postback event occurs, the hash code will be re-established and must match the original hash code. In this way, it can be effectively checked whether the ViewState can be tampered with during the transmission process. By default, the .NET Framework uses the SHA1 algorithm to generate ViewState hash codes. In addition, you can also select the MD5 algorithm by setting <machineKey> in the machine.config file, as shown below: <machineKey validation="MD5" />. The performance of the MD5 algorithm is better than that of the SHA1 algorithm, but it is also not secure enough.
· The encryption mechanism
uses encryption to protect the actual data values in ViewState fields. First, EnableViewStatMAC="true" must be set as described above. Then, set the machineKey validation type to 3DES, that is, <machineKey validationKey="AutoGenerate" decryptionKey="AutoGenerate" validation="3DES" />, which instructs ASP.NET to use the 3DES encryption algorithm to encrypt the ViewState value.
(4) View State Blocking
The above content introduces some basic knowledge of view state. However, some readers may be confused: What if the view state data becomes very large in some cases? This will obviously have some unintended consequences. To this end, ASP.NET 2.0 adds a new feature called "view state blocking". If the amount of data in the view state becomes too large, view state chunking automatically breaks the data into multiple chunks and places the data in multiple hidden form fields.
To enable view state chunking, set the MaxPageStateFieldLength property to the maximum size allowed in a single view state field, in bytes. When the page is posted back to the server, the page parses the view state string during the page initialization phase and restores the property information in the page. The default setting is -1, which means there is no maximum size and the view state will not be divided into chunks.
(5) Advantages and Disadvantages
Using view state has the following three advantages: 1. It consumes less server resources (compared to Application and Session). Because the view state data is written to the client computer. 2. Easy to maintain. By default, the .NET system automatically enables maintenance of control state data. 3. Enhanced security features. Values in view state are hashed, compressed, and encoded against the Unicode implementation, which is more secure than using hidden fields.
Using view state has the following three disadvantages: 1. Performance considerations. Because view state is stored in the page itself, if a large value is stored, the user may still be slowed down when displaying and sending the page, even if the view state is chunked. 2. Equipment limitations. Mobile devices may not have enough memory capacity to store large amounts of view state data. Therefore, when moving server controls on a device, a different implementation method is used. 3. Potential security risks. View state is stored in one or more hidden fields on the page. Although view state stores data in a hashed format, it can be tampered with. If you view the page output source directly, you can see information in hidden fields, leading to potential security issues.
Typical applications
In the process of developing server controls using ASP.NET 2.0 technology, there are many aspects where view state can be used. It is common to use the ViewState dictionary to implement server control properties. ViewState is of type System.Web.UI.StateBag - a dictionary of key/value pairs in which server control property values can be stored. The following uses a typical example to illustrate the application method of ViewState.
In the custom server control LabelInViewState, two properties Text and TextInViewState are implemented. The former is created using private variables, and the latter is implemented using ViewState. They are all used to get or set text content. The source code of the custom control implementation file LabelInViewState.cs is as follows.
using System;using System.Collections.Generic; using System.ComponentModel;using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls;namespace WebControlLibrary{ [DefaultProperty("Text")] [ToolboxData("<{0}:LabelInViewState runat=server></{0}:LabelInViewState>")] public class LabelInViewState : WebControl { private string _text; //Implement the Text attribute public string Text { get { return (_text == null) ? string.Empty : _text; } set { _text = value; } } //Use ViewState to implement the TextInViewState property public string TextInViewState { get { String s = (String)ViewState["TextInViewState"]; return ((s == null) ? String.Empty : s); } set { ViewState["TextInViewState"] = value; } } // Override the RenderContents method protected override void RenderContents(HtmlTextWriter output) { output.Write("Text = "); output.Write(Text); output.Write("<br/>"); output.Write("TextInViewState = "); output.Write(TextInViewState); } } } |
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ Register Namespace="WebControlLibrary" Assembly="WebControlLibrary" TagPrefix="sample" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> void Button1_Click(object sender, EventArgs e) { demoLabel.Text = TextBox1.Text; demoLabel.TextInViewState = TextBox2.Text; } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Use view state ViewState </title> </head> <body style="font-size: small;"> <form id="form1" runat="server"> <div> Name: |
The above code displayed on the page includes two text boxes, two buttons, and a custom server control LabelInViewState. As shown in the event handler Button1_Click, when the "Submit" button is clicked, the LabelInViewState control will obtain the text in the text box and display it. The application renderings are shown in Figures 1 and 2.
Figure 1 Click the submit button | Figure 2 Click the reload button |