Asp. NET Server control view state

Source: Internet
Author: User
Tags hash numeric md5 numeric value serialization sha1 client
It is necessary to maintain state information for Web pages and their controls. However, because Web applications are created at the top level of the HTTP protocol, this is a stateless protocol, so maintaining state information becomes very difficult. To address this problem, the ASP.net 2.0 technology offers a variety of solutions, such as using session, cookies, view state, control state, hidden fields, query strings, personalized User Configuration (profile), and so on. Maintaining state information is also important for creating server controls using ASP.net 2.0 technology, whose primary solution is to take advantage of 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 application.

   View State Overview

View state is a very important technique that enables controls on pages and pages to maintain state information from the server to the client and back to the round trip from the client. This allows you to create a stateful and continuously executed page effect on the web's stateless environment. This section focuses on the running mechanism of view state, application methods, stored data types, performance and security, view state chunking (This is the new feature of ASP.net 2.0), and advantages and disadvantages.

(1) Operating mechanism

The specific running process of view state is: whenever a user requests an. aspx page, the. NET Framework first serializes the state data of the related control into a string, and then it is sent to the client as the value value of the hidden field named __viewstate. If the page is requested for the first time, then the server control will also be executed for the first time, and the hidden field named __viewstate contains only the default information for the control, usually null or null. In a subsequent loopback event, the property state that the server control is available in the front loopback is saved in viewstate. This enables the server control to monitor the status of the loopback event that is currently being processed. These processes are made up of. NET Framework, the execution of the. aspx page is effective for the user.

(2) Stored data types

View state can store multiple types of data, and in order to improve efficiency, view state itself includes a set of optimized serialization methods for common types. The default supported data types for view state serialization 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 that contain the types listed above. Therefore, when using view state in a control, you should try to limit the use of the above simple data types and the optimized types. Here, you need to highlight the custom type converter TypeConverter, which provides a uniform way to convert the type of a value to another type and to access standard values and child properties. For example, you can use TypeConverter to convert a string to a numeric value, or to convert a numeric value to a string. If there is no type converter, then the page frame is used. NET Framework provides a binary serialization capability to serialize objects, which is a very resource-intensive process.

(3) Performance and security

When using view state, the object must be serialized before being deserialized by a postback. Therefore, we must understand the content about viewstate performance. By default, the control's viewstate is enabled, and if you do not need to use ViewState, it is best to turn it off. The following conditions will no longer be required viewstate: (1) The control does not define a server-side event (at which time the control event is a client event and does not participate in the loopback); (2) The control has no dynamic or data-bound property value. The way to turn off view state is to set the value of the control's enableviewstate to "false", that is, enableviewstate= "false".

By default, when the content of view state is sent to the client when the compilation is run, the reader will see the __viewstate hidden field contents in the page's HTML code. This is some meaningless string, the result of the. NET Framework encoding related content by Base64 bit encoding. They are sent back and forth between the client and server by plaintext. In some cases, such as sensitive content involving passwords, accounts, connection strings, and so on, it is not safe to use the default method. To this end,. NET Framework provides two security mechanisms for ViewState:

· Calibration mechanism:

You can indicate by setting the enableviewstatemac= "true" property. NET Framework appends a hash code to the ViewState data (the hash code is a SHA1 type with 160 bits in length, thus severely impacting performance). When the postback event occurs, the hash code is re-establish, and it must match the original hash code. In this way, it is possible to effectively test whether ViewState can be tampered with during transmission. By default,. NET Framework uses the SHA1 algorithm to generate the ViewState hash code. Alternatively, you can select the MD5 algorithm by setting <machineKey> in the Machine.config file, as follows: <machinekey validation= "MD5"/>. The performance of the MD5 algorithm is better than the SHA1 algorithm, but it is also not safe enough.

· Encryption mechanism

Use encryption to protect the actual data values in the ViewState field. First, you must set enableviewstatmac= "true" as described above. Then, set the MachineKey validation type to 3DES, that is, <machinekey validationkey= "AutoGenerate" decryptionkey= "AutoGenerate" validation= "3DES"/>, which indicates that ASP.net uses the 3DES encryption algorithm to encrypt viewstate values.

(4) View-state chunking

The above describes some of the basics of view state. However, some readers may be puzzled: what if, in some cases, the view state data becomes large? It is obvious that there will be some unintended consequences. To do this, ASP.net 2.0 adds a feature called View state chunking. If the data in the view state is too large, the view-state chunking automatically divides the data into chunks and places the data in a number of hidden form fields.

To enable view-state chunking, set the Maxpagestatefieldlength property to the maximum size, in bytes, allowed in a single view state field. When the page is sent back to the server, the page analyzes the view-state string at the page initialization stage and restores the property information in the page. The default setting is-1, which means that there is no maximum size and the view state is not partitioned into multiple blocks.

(5) Advantages and disadvantages

Using view state has the following 3 advantages: First, less server resources are consumed (compared with application, session). Because the view state data is written to the client computer. Second, easy to maintain. By default,. NET system automatically enables maintenance of control state data. Third, the enhanced security features. Values in view state are hashed and compressed, and encoded for Unicode implementations, with a higher security than using hidden fields.

Using view state has the following 3 disadvantages: first, performance considerations. Because view state is stored in the page itself, if a large value is stored, the user may still be slow to display the page and send the page even if the view state is chunking. Second, the equipment limit. Mobile devices may not have enough memory capacity to store large amounts of view-state data. Therefore, when you move a server control on a device, you use a different implementation method. Third, the potential security risks. View state is stored in one or more hidden fields on the page. Although view state stores data in hashing format, it can be tampered with. If you view the page output source directly, you can see the information in the hidden field, which causes potential security problems.

Typical applications

There are many aspects that can be used to view state during server control development using ASP.NET 2.0 technology. It is common to implement server control properties using the ViewState dictionary. ViewState is a SYSTEM.WEB.UI.STATEBAG type-a dictionary of key/value pairs that can be stored in the viewstate of a server control. The following is a typical example of how ViewState is applied.

In the custom server control Labelinviewstate, two properties text and Textinviewstate are implemented. The former is created using a private variable, and the latter is implemented using ViewState. They are both used to get or set text content. The custom control implementation file LabelInViewState.cs the source code as shown below.

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; Implementing the Text Property
public string Text {
get {
return (_text = null)? String. Empty: _text;
}
set {_text = value;}
}
Using ViewState to implement Textinviewstate properties
public string Textinviewstate {
get {
string s = (string) viewstate["Textinviewstate"];
Return ((s = = null)? STRING.EMPTY:S);
}
set {viewstate["textinviewstate"] = value;}
}
Overriding the RenderContents method
protected override void RenderContents (HtmlTextWriter output) {
Output. Write ("Text =");
Output. Write (Text);
Output. Write ("<br/>");
Output. Write ("textinviewstate =");
Output. Write (textinviewstate);
}
}
}

As shown in the code above, the control implements two property text and Textinviewstate. The Text property uses the private variable _text creation, which cannot hold the state information of the property. The Textinviewstate property uses ViewState, which, through the set accessor, writes the property value to the viewstate["Textinviewstate" object and, through the get accessor, from the object viewstate[" Textinviewstate "] to get the property value. This is the simplest way to view state processing. When using ViewState as a property store, custom server controls can perform simple state information management on their own, such as TrackViewState, SaveViewState, LoadViewState, and so on. Of course, developers can also customize the state management logic program by overriding the method. In this case, the view state management process is made up of. NET Framework is completed automatically.

The following is an enumeration of the Default.aspx file source code created to test the above custom server controls.

<%@ 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>
<title> use view state viewstate </title>
<body style= "Font-size:small;" >
<form id= "Form1" runat= "Server" > <div> name:

The above code shows that there are two text boxes, two buttons, and a custom server control labelinviewstate on the page. As shown in event handler button1_click, when you click the Submit button, the Labelinviewstate control gets the text in the text box and displays it. The application effect diagram is shown in Figure 1 and Figure 2.


Figure 1 Click the Submit button

Figure 2 Click the overload button

As shown in Figure 1, when the user fills out the text in two text boxes, and clicks the submit button, it causes the page to return. At this point, the text content is submitted to the server and participates in the Button1_Click event handler. In this way, the Labelinviewstate control displays the text and Textinviewstate property values. After that, when the user clicks the overload button, the contents of the text box are still committed to the server, but because there is no corresponding event handler, the Labelinviewstate control displays only the status information that already exists (that is, the state saved after clicking the Submit button), that is, the Text property value is empty. The Textinviewstate property value is tom@tom.com. The above procedure shows that the Textinviewstate property value is stored in the view state viewstate, so the property is worth keeping while the page is round, and text simply uses the private variable, so state information cannot be persisted. Also, note that the above effect can be achieved by default, because the page has view state EnableViewState = "true".

   Summary

This paper mainly introduces the basic concept of view state, and illustrates the application method through a typical example. Perhaps some readers have realized that if you disable the view state of a page or control by setting EnableViewState = "false", then the properties of the server control above textviewstate not be used? This is indeed a flaw in view state. However, this is not to say that it is impossible to solve the problem. In the next section, I'll introduce another new ASP.net 2.0, a technical feature that is very similar to view state--control state--that can solve the problem of disabling view state.


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.