Use viewstate improved by ASP. NET 2.0 to speed up your website

Source: Internet
Author: User
Tags printable characters

How viewstate works

Improvement of ASP. NET 2.0 viewstate

Use the control status maintenance Function

Performance Considerations

This article uses the following technologies:
ASP. NET, C #

CodeDownload:
Viewstate.exe(122kb)

Content on this page
Basic Principle of viewstate
Viewstate Problems
Viewstate improvement in ASP. NET 2.0
Control status
Declarative data source and viewstate
Summary

If you are an experienced ASP. NET developer, you may shudder when you mention viewstate, because you think of a large amount of base64 encoded data inhaled through the "cocktail straw. Unless you take the steps to prevent it, a large amount of auxiliary data will be stored in a hidden field named _ viewstate on most ASP. NET pages. In most cases, you do not even need this field. Browse your favorite sites generated using ASP. NET to view the pageSource codeTo calculate the number of characters hidden in the _ viewstate field. I tried it. The number is 800 to 7,800 characters.

Of course, viewstate has an important role in ASP. NET. If used properly, it can simplify page development and improve interaction between users and sites. If you ignore it, it can significantly increase the site response size. When the connection speed is slow, your response time will be slower. The release of ASP. NET 2.0 brings about some improvements to the viewstate mechanism, which makes viewstate easier to use and does not affect site performance. These improvements include reducing the number of codes, separating the travel status from the content into the status, and intelligently integrating data binding controls.

Basic Principle of viewstate

Before introducing the improvement of ASP. NET 2.0 viewstate, it is appropriate to briefly summarize the usage and implementation of viewstate in the current version. Viewstate solves a specific problem for ASP. NET developers-retaining the status of controls on the server side that do not form elements. This is important because most of the server-side control models in ASP. NET are generated based on this assumption, that is, if the user sends back to the same page, all the controls remain unchanged. That is to say, if you modify the content of any control during request processing and any subsequent post requests return to the same page, you can rely on the modifications that still exist. As an example of an active viewstate, try to runFigure 1The displayed page.

Each time you press the submit button, the value of _ sum ranges progressively. Because viewstate retains the previous value during the request, it will display 1, 2, 3, 4, and so on starting from the last displayed value. If you want to know what happens when viewstate is unavailable, add enableviewstate = 'false' as an attribute of the range element. Because the previous range value is not propagated during request processing, no matter how many times the page is published, the value is 1.

In ASP. NET, viewstate completes the control-based programming model. If no viewstate exists, some controls (such as text boxes and drop-down lists) remain in the status during the POST request, while other controls do not, using these controls in different states to record some special situations is frustrating. With viewstate, developers can focus on programming models and user interfaces without worrying about status persistence. You can also hash or encrypt viewstate to prevent user tampering or decoding. For more information about this topic, see Chapter 19th of the online book securing your ASP. NET application and Web services.

Another important aspect of using viewstate is to publish server-side change events in the control. If you change the value in the text box or switch to the selected element in the drop-down list, you can register an event for processing.ProgramWhen an event is triggered, the code is executed. These controls compare the current value with the previous value. If there is any process booking change event, the previous value is implicitly stored in viewstate. If the viewstate of a control is disabled and you are processing the change notification event of the control, the change notification event is not triggered correctly because it is always assumed that the previous value is the same as the default value of the form.

Back to Top

Viewstate Problems

As I mentioned earlier. XThere are many problems with viewstate. By default, it is enabled, unless you know to find and disable it when it is not needed, it can significantly increase the page rendering data volume. When you use a data binding control, all controls use viewstate to save the status after sending back, which becomes an exception. As a simple and vivid example, considerFigure 2Shows the ASP. NET page.

This page has a DataGrid Control, which is bound to the simple query result of the authors table in the pubs database. If you run this page (make necessary corrections to the connection string) and view the viewstate field, you may be surprised to find that it contains more than 12,000 characters. When you view the page content and realize that the actual number of characters required to display the entire table content in the browser is about 1,600, you will be even more surprised. One of the reasons for this result is that viewstate not only encodes data, but also encodes the data type (metadata). Similarly, base64 encoding generally increases the space system overhead by about 33%. In addition, a large amount of system overhead is only used to reserve the status of the control after the POST request. This seems to be out of proportion to the time, and we must do our best to avoid it.

Obviously, if you care about the response size, it is important to decide when to disable the viewstate of the control. The example just now is a typical case where viewstate is propagated but never used. This is the primary rule recommended for optimizing the viewstate usage of the site: if the control content is filled on each request page, it is generally safe (WISE) to disable the viewstate of the control.

On the other hand, you may decide to use viewstate to retain the control state, and fill in the control content (only through subsequent post requests) only when the page's first GET request is made ). This eliminates the need for a round-trip to any backend data source. By modifying my page to use this conclusion, I changed the onload method so that it checks the ispostback flag before filling the DataGrid, as shown in figureFigure 3.

Of course, there are some other options that may be better, such as Cache Server query results, and re-bind the control each time a request is sent. You can weigh the location of state storage and the importance of specific architectures and applications.

You may have noticed that I have carefully mentioned that if the control content is filled in every request to the page, it is safe to disable viewstate "normal. The exception is that some controls retain both viewstate and general state. As described above, the drop-down list and text box controls use viewstate to store previous values to correctly publish change notification events on the server. Similarly, the DataGrid class uses viewstate to publish, edit, and sort events by page. Unfortunately, viewstate cannot be disabled if you want to use the DataGrid functions such as sorting, paging, or editing. For developers who try to generate a fast and effective site, the server-side control viewstate is not all exclusive. It is ASP. NET 1.XServer-side control model.

Back to Top

Viewstate improvement in ASP. NET 2.0

Since I have outlined these issues, it is time to discuss all the improvements in ASP. NET 2.0. The first is the total size of viewstate serialization. In ASP. NET 1.XThe serialization of the two strings into the viewstate buffer is as follows:

 
<P <L <string1; >;l <string2 ;>;>;

ASP. NET 1.XThe viewstate serialization format used in is a tuples. It consists of three hierarchical sets and sequence pairs with greater than or less than signs. The letters before the marker represent the type of the stored object (t = triplet, P = pair, I = integer, L = arraylist, etc ). Each child element in a greater than or less than a number is separated by a semicolon. This is an interesting serialization format, a bit like a compressed XML. However, if you care about space, it is not the most effective serialization format (just a little better than XML ).

ASP. NET 2.0 changes the serialization format. In ASP. NET 2.0, the serialization of the two identical strings into the viewstate buffer is shown in the following code line:

 
[] [] String1 [] string2

At least, this is similar to the format presented by the browser. Square brackets are actually non-printable characters. If we use Unicode character reference for rewriting, it will become the encoding shown below:

 
& #15; & #5; string1 & #5; string2

ASP. NET 2.0 uses some non-printable characters to identify the start of an object and express the object type, rather than using printable character sets ("<", ">", "; "," L "," I "," P ", etc.) to split the objects in the viewstate stream.

The object stored in viewstate is separated by non-printable characters for two purposes. The first objective is to improve the efficiency of lexical analysis when parsing viewstate strings, because it does not need to match characters or parse tags. The second and more important purpose is to reduce the number of characters used for object encoding in viewstate. In a simple example of encoding two strings, the first encoding method uses 16 separated characters, and the 2.0 format uses three. This role quickly becomes a compound and has a major impact.

For example, if we place a DataGrid on the form and bind it to the authors table of the pubs database, as shown inFigure 3As shown in, then 1.XThe viewstate string in is 12,648 characters in size. If this is also done in 2.0, the viewstate size is reduced to 6,728 characters, which is almost halved. Figure 4 shows ASP. NET 1.XThe space required for viewstate in ASP. NET 2.0 and the actual number of characters displayed on the page for different input sizes. In this case, the authors table adds additional rows to the 500 rows, reaching 2,000 rows.

Figure 4 Comparison of viewstate size

With the release of ASP. NET 2.0, you can expect to immediately reduce the viewstate size without any special work. This does not mean that you should stop considering whether viewstate is required for the control to work normally, because it still has a great impact on the Response size, which is obvious in Figure 4. However, the next improvement of viewstate can potentially save more.

Back to Top

Control status

Prerequisites: ASP. NET 1.XThe most frustrating aspect of using server-side controls is that viewstate is both non-exclusive and completely unavailable. Control behavior, such as the page in the DataGrid or the selected change notification in the text box, you need to enable viewstate to run properly. I'm sure the prospect of enabling viewstate in any DataGrid is frustrating to everyone. In ASP. NET 2.0, Microsoft splits viewstate into two independent and different categories to solve this special problem: viewstate and control state.

The control state is another type of hidden state, which is reserved for maintaining the core behavior functions of the control, while the viewstate only contains the state of maintaining the control content (UI. Technically, the control state is stored in the same hidden field as viewstate (only another leaf node at the end of the viewstate hierarchy ), however, If you disable the viewstate of a specific control or the entire page, the control state will still spread. The good thing about implementing this technology is that we can now improve ASP. NET 2.0 optimizes the original principle of viewstate to make it more robust: if the control content is propagated on each request page, you should disable the viewstate of the control.

As long as the control builder correctly divides its status into behavior states (to maintain core functions) and UI states (to retain content), it should strictly abide by this principle. I recommend that you follow this principle when using ASP. NET 2.0, but the DataGrid has not been restructured to retain the behavior status in the control status. Fortunately, the new gridview is the logical successor of the DataGrid, And it correctly uses the control status like the new versions of the textbox and dropdownlist controls.Figure 5The list of currently used controls and their storage properties are displayed for your reference. With the final release of ASP. NET 2.0, this list may change.

If you are willing to study ASP. NET 2.0 new controls how to use the control status and viewstate, you can use a utility I wrote called view State decoder, which is used to display all the viewstate and control status on a given page.Figure 6A screen snapshot of the active utility is displayed. You can download this program from the link at the top of this article. Note that this application depends on the encoding characters currently used by viewstate and may change before the final version is released.

The usage model of the control status is not as convenient as that of the viewstate Control Generated by you. You must override the loadcontrolstate and savecontrolstate Virtual Methods to manually manage your collection of objects mapped to the control state, rather than providing an indexed status package for insertion and removal. Another thing you must do is call the page. registerrequirescontrolstate method during initialization so that the page can ask the control status at the correct time. It is more difficult to store options in the control state than in viewstate, because you cannot disable it (the control state has a selection model that also has performance benefits ). Developers should carefully consider before storing any status, because it is always added to the rendered page.Figure 7Display a custom control that stores a string in the control state (in this example, its color ).

When you decide what content is stored in the control status and viewstate, remember that the behavior status should be different from the content or UI status. Content such as attributes and datasets should generally be stored in viewstate, rather than migrated to the control state. The State that triggers server events is the most typical state stored in the control state.

Back to Top

Declarative data source and viewstate

There is a small problem with our viewstate Optimization Principle-you often don't know whether the control content is being filled in each request. Using declarative data sources in ASP. NET 2.0 means that you do not need to explicitly connect data source attributes to datareader or dataset when binding data to a control and call databind. Instead, you can place a data source on the page and point the control to the data source. For example, use the new gridview class bound to the authors table in the pubs database and the related sqldatasource (seeFigure 8). If you run this page, you will find it works. The gridview and its corresponding data sources can understand when to interact. Before the page is displayed, the gridview is filled with data from the data source, and the entire authors table may be displayed on the client.

In this simple case, we have not disabled the viewstate of the gridview, so you may think that we once again only use viewstate to store data that has never been used. Fortunately, the ASP. NET 2.0 engine does the right thing. When viewstate on the control is available, it will return to the database without any annoyance.

Similarly, if viewstate on the gridview is disabled, data binding to the data source will occur in each request, including the post back request. This function is set in the databoundcontrol base class. The adrotator, bulletedlist, checkboxlist, dropdownlist, ListBox, radiobuttonlist, gridview, detailsview, and formview controls inherit this function. These controls demonstrate the smart usage of viewstate when bound to a declarative data source.

Back to Top

Summary

The next version of ASP. NET promises many improvements to Web developers. It is not only more likely to take a good rest at night, but will not cause base64 encoding data to overwhelm the nightmare of web forms. With more compact serialization formats, separation of behavior states and UI states, and smart interaction between data-bound controls and declarative data sources, the nightmare of viewstate can only become a dream.

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.