A preliminary study of ASP.net ViewState when Susan Warren Microsoft Corporation November 27, 2001 talked to developers who had just contacted the ASP.net page, the first question they usually asked me was: "That View What exactly is state? "The feeling in their tone was like when I came to an exotic restaurant where the waiter served a dish I had never seen before--both puzzled and curious. But someone must think it's good, otherwise it won't be offered. So I'll try it first, maybe I'll like it, even though it does look weird! The same is true for ViewState, but if you adapt to its style, you'll find that in many cases you'll be happy to use ViewState in your own asp.net application because it helps you do more work with less code. However, there are times when the ViewState is completely abandoned. Here we will explain the two cases separately, but let us first answer what is ViewState this question.
Answer: ViewState is used to maintain the UI state of the pageThe Web is stateless, asp.net pages are not stateful, and they are instantiated, executed, rendered, and processed during each round trip to the server. As a Web developer, you can add states by using well-known techniques, such as storing the state on a server in session state, or uploading a page back to itself. The following is an example of the registered form in Figure 1.
Figure 1: Restoring the Return form valueAs you can see from the image above, I have chosen an invalid value for the light meal. This form is as friendly as most forms on the Web, and it displays a useful error message and an asterisk next to the field where the error occurred. Also, the form shows all the valid values I entered in the other text boxes and Drop-down lists. This is possible in some way because HTML form elements send their current values from the browser to the server in the HTTP header. You can use ASP.net tracing to view the form values that are returned, as shown in Figure 2.
Figure 2:http The return value in the form (shown by asp.net tracking)Before ASP.net, restoring values to form fields through multiple postbacks is entirely the responsibility of the page developer who will have to pick up the pass-through from the HTTP form and push it back into the field. Fortunately, ASP.net can now automate this task, eliminating a tiresome job for developers, and no need to write a lot of code for the form. But this is not ViewState. ViewState (English) is a mechanism that asp.net use to track server control state values, otherwise these values will not be returned as part of the HTTP form. For example, by
LabelThe text displayed by the control is saved in ViewState by default. As a developer, you can bind data, or when the page is first loaded, only the
LabelProgrammatically, the label text is automatically populated from the ViewState in the subsequent back crosses. Thus, in addition to reducing tedious work and code, ViewState often reduces the number of round-trip times to the database.
The working principle of ViewState
ViewState is really no mystery, it is a hidden form field managed by the ASP.net page framework. When ASP.net executes a page, the ViewState value and all controls on the page are collected and formatted into a coded string, which is then assigned to the Value property (that is) of the hidden form field. Because the hidden form field is part of the page that is sent to the client, the ViewState value is temporarily stored in the client's browser. If the client chooses to pass the page back to the server, the ViewState string is also returned. In Figure 2 above you can see the ViewState form field and its return value. After the postback, the asp.net page frame resolves the ViewState string and populates the ViewState property for the page and individual controls. The control then uses the ViewState data to revert itself back to its previous state. There are three small issues worth noting about ViewState.
- If you want to use ViewState, you must have a server-side form marker () in the ASPX page. form fields are required so that hidden fields containing ViewState information can be passed back to the server. Also, the form must be a server-side form, so that the ASP.net page frame can add hidden fields when the page is executed on the server.
- The page itself stores about 20 bytes of information in ViewState, which is used to distribute postback data and ViewState values to the correct control at the time of the postback. Therefore, even if the page or application disables ViewState, you can still see a small amount of remaining bytes in ViewState.
- When the page does not return, you can remove the ViewState from the page by omitting the server-side tag.
Make full use of ViewStateViewState provides a magical way to track the state of a control across the postback because it does not use server resources, does not time out, and is applicable to any browser. If you're writing a control, you'll definitely need to know how to maintain state in the control (in English). Developers can also use ViewState in almost the same way when they write pages, but sometimes the page contains UI state values that are not stored by the control. You can track values in ViewState, and the syntax for using the programming syntax for sessions and caching is similar:
[Visual Basic]
' Save in ViewState ViewState (' SortOrder ') = ' DESC ' reads Dim ViewState As String = CStr (SortOrder ("ViewState") from SortOrder)
[C #]
Save in ViewState viewstate["SortOrder" = "DESC";//Read String ViewState = (string) SortOrder "viewstate[" from SortOrder];
Consider the following example: To display a list of items on a Web page, each user needs a different sort of list. The list of items is static, so you can bind these pages to the same cached dataset, which is only a small part of the user-specific UI state. ViewState is ideal for storing this type of value. The code is as follows:
[Visual Basic]
Storing non-control state in ViewState
This example stores the current sort order for a column of static data in ViewState.
Click the link in the column header to sort the data by that field.
Clicking the link again will be sorted in reverse order.
The following are the Testdata.xml code referenced in the two preceding snippets:
0736 new Moon Books boston ma usa 0877 binnet & Hardley Washington DC USA 1389 algodata infosystems berkeley ca usa 1622 five Lakes publishing chicago il usa 1756 ramona Publishers dallas tx usa 9901 GGG&G Muenchen germany 9952 scootney Books New York &nbsP; ny usa 9999 lucerne Publishing Paris France
Select a session state or ViewState?
In some cases, saving a state value in ViewState is not the best choice, and the most common alternative is session state, which is generally more applicable to:
- a lot of data. because ViewState increases the size of the page that is sent to the browser (the HTML payload) and also increases the size of the returned form, it is not appropriate to store large amounts of data.
- security data that is not displayed in the UI. Although ViewState data has been encoded and can optionally be encrypted, it is safest to never send data to the client. Therefore, a session is a more secure choice. (Because the database requires additional credentials to authenticate, it is more secure to store the data in the database.) You can add SSL to get a more secure link. However, if the private data is already displayed in the UI, you should have confirmed the security of the link. In this case, putting the same value into the ViewState does not degrade security.
- an object, such as a DataSet, that has not been serialized into ViewState. the ViewState serializer optimizes only a small number of commonly used object types, as shown below. Other serializable types may be retained in the ViewState, but the speed will be slow and a very large ViewState will be generated.
Session state viewstate Do you use server resources? Do you have a timeout? Yes, 20 minutes later (default) do you want to store all. NET types? Do you only support: String, Integer, Boolean, Array, ArrayList, Hashtable, and custom TypeConverter increase the HTML payload? No is
Use ViewState for optimal performance
When using ViewState, each object must be serialized into the ViewState and then deserialized by a postback, so the use of ViewState is not without cost. However, if you follow some simple principles to control the cost of ViewState, you typically do not have a significant performance impact.
- Disable ViewState when it is not needed. This issue is described in more detail in the "Reducing Use of ViewState" section below.
- Use an optimized ViewState serializer. The types listed above have specialized serializers that run quickly and are optimized to produce small ViewState. If you want to serialize a type that is not listed above, you can create a custom typeconverter to significantly improve its performance.
- Minimize the use of objects and, if possible, minimize the number of objects placed in ViewState. For example, instead of using a two-dimensional string array (name/value with the same number of objects as the length of an array), use a two string array (only two objects). However, before you store two known types in ViewState, there is no performance improvement between the two, because doing so is actually equivalent to the cost of two conversions.
reduce the use of ViewStateViewState is enabled by default and is determined by each control, not the page developer, to determine what is stored in the ViewState. Sometimes, this information is of little use to the application. While it's harmless, it can significantly increase the size of the pages sent to the browser. So if you don't need to use ViewState, it's best to turn it off, especially when the ViewState is big. You can turn off ViewState on a per-control, per-page, or per-application basis. ViewState is no longer required in the following situations: page control
- The page is not passed back to itself.
- The event that is not handled by the control.
- Controls do not have dynamic or data-bound property values (or 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, which is useful when a complex operation (such as a complex search) is needed to get the data. However, this behavior of the DataGrid sometimes makes ViewState a liability. For example, here's a simple page that falls into this scenario. Because the page is not passed back to itself, it does not need ViewState.
Figure 3: A simple page with DataGrid1 lessviewstate.aspx
When ViewState is enabled, this small grid adds more than 3,000 bytes of HTML payload to the page! You can see this clearly by using ASP.net tracing (English) or by viewing the source code of the page sent to the browser, as shown in the following code.
See! The ViewState of the grid is disabled, and the payload of the same page is greatly reduced:
Here is the complete lessviewstate code for Visual Basic and C #:
[Visual Basic]
Reduce page "HTML payload" by disabling ViewState
[C #]
Reduce page "HTML payload" by disabling ViewState
Disable ViewState
In the example above, I pass the grid's
EnableViewStateProperty set to False disables ViewState. You can disable ViewState for a single control, an entire page, or an entire application, as follows: Each of the controls (on the markup) per page (in instructions) per application (in Web.config)
make ViewState more secureSince ViewState is not formatted as clear text, some people sometimes think it is encrypted, but not. Instead, ViewState only Base64 encoding to ensure that the value does not change during the round trip, regardless of the response/request encoding used by the application. You can add two kinds of ViewState security levels to your application:
- Tamper Resistant
- Encryption
It should be noted that ViewState security has a direct impact on the time it takes to process and render asp.net pages. Simply put, the higher the security, the slower the speed. Therefore, do not add security for ViewState if you do not need it.
Tamper Resistant
Although the hash code does not guarantee the security of the actual data in the ViewState field, it can significantly reduce the likelihood that someone has cheated an application through ViewState, that is, preventing the return application from generally prohibiting the user from entering a value. Can be set by setting
enableViewStateMacproperty to instruct ASP.net to append a hash code to the ViewState field:
You can set enableViewStateMac at the page level or at the application level. At the time of return, ASP.net will generate a hash code for the ViewState data and compare it to the hash code stored in the postback value. If two hash codes do not match, the ViewState data is discarded and the control reverts to its original setting. By default, ASP.net uses the SHA1 algorithm to generate the ViewState hash code. Alternatively, you can select the MD5 algorithm by setting it in the Machine.config file, as follows:
Encryption
You can use encryption to protect the actual data values in the ViewState field. First, you must set enableviewstatmac= "true" as described above. Then, will MachineKey
ValidationType is set to
3DES。 This instructs ASP.net to use the Triple DES symmetric encryption algorithm to encrypt the ViewState value.
ViewState security in the WEB domain
By default, ASP.net creates a random authentication key and is stored in the Local Security Authority (LSA) for each server. To verify the ViewState field created on another server, two server
validationkeyMust be set to the same value. If you want to ViewState security settings for applications running in the WEB domain configuration in one of these ways, you need to provide a unique, shared authentication key for all servers. The validation key is a random string of 20 to 64-bit password-enhanced bytes, expressed in 40 to 128 hexadecimal characters. The longer the key is secure, the 128-character key is recommended (if supported by the computer). For example:
[/b]validationkey=] f3690e7a3143c185ab1089616a8b4d81fd55dd7a69eeaa3b32a6ae813eceecd28dea66a23bee42193729bd48595ebafe2c2e765be77e006330bc3b139 2d7c73f "/>
The System.Security.Cryptography namespace includes
RNGCryptoServiceProviderclass, which can be used to generate this string, as shown in the following generatecryptokey.aspx example:
generate random encryption key
40-byte 128-byte
copy and paste the results of the build
SummaryASP.net ViewState is a new state service that allows developers to track UI state based on each user. ViewState is no mystery, it just uses an old Web programming trick: To pass the state back and forth in a hidden form field and apply it directly to the page-handling frame. But the effect is very good-just write and maintain very little code in a web-based form. The user may not always need it, but I think you'll find that when you need it, ViewState is a very satisfying feature of the many ASP.net new features available to page developers.