Speed up Web site with asp.net 2.0 improved ViewState

Source: Internet
Author: User
Tags base64 dsn range
Asp.net| Speed If you're an experienced asp.net developer, you might shudder to mention ViewState, because you're thinking of a lot of Base64 encoded data inhaled through "cocktail straws." Unless you take steps to prevent it, most asp.net pages will have a large number of secondary data stored in a hidden field named __viewstate, most of which do not even require this field. Browse your favorite sites generated with ASP.net, view the page source code, and calculate the number of characters hidden in the __viewstate field. I tried it for a number of 800 to 7,800 characters.

Of course, ViewState has an important role to play in asp.net. If used properly, it can simplify page development and improve user interaction with the site. If you ignore it, it can significantly increase the site response size and make your response time slower when the connection speed is slow. The release of ASP.net 2.0 brings some improvements to the ViewState mechanism, which makes ViewState easier to use and does not hinder site performance. These improvements include reducing the number of encodings, separating the behavior state from the content with control state, and intelligently integrating data-bound controls.

  ViewState Fundamentals

Before introducing the improvement of ASP.net 2.0 ViewState, it is appropriate to briefly summarize the purpose and implementation of ViewState in the current version. ViewState solves a specific problem for asp.net developers-preserving the state of a control that does not form an element on the server side. This is important because most of the server-side control models in ASP.net are based on the assumption that if the user is sending back to the same page, all the controls remain in their state. That is, if you modify the contents of any control during the processing of a request, you can rely on those modifications that are still present when any subsequent POST requests return to the same page. As an active ViewState example, try running the code shown below.

<%@ Page language= "C #"%>
<script runat= "Server" >
protected override void OnLoad (EventArgs e)
{
int val = Int. Parse (_sum. InnerText);
_sum. InnerText = (val+1). ToString ();
Base. OnLoad (e);
}
</script>
<body>
<form runat= "Server" >
<span id= "_sum" runat= "Server" >0</span>
<br/>
<input type= "Submit"/>
</form>
</body>

The _sum range value increments each time the Submit button is pressed. Because ViewState retains its previous value during the request, it displays 1, 2, 3, 4, and so on, starting with the last displayed value. If you want to know what happens when ViewState is not available, try adding enableviewstate= ' false ' as a property of the scope element. Because the previous range value was not propagated when the request was processed, the value is 1 regardless of how many times the page is published.

In ASP.net, ViewState completes a control-based programming model. If there are no ViewState, some controls, such as text boxes and Drop-down lists, remain state during POST requests and other controls are not persisted, and it is frustrating to use controls that vary in their state to record special situations. With ViewState, developers can focus on the programming model and user interface without worrying about state retention. ViewState can also be hashed or encrypted to prevent tampering or decoding by the user.

Another important thing to use ViewState is to publish server-side change events in the control. If the user changes the value in the text box or toggles the selected element in the Drop-down list, you can register an event handler and execute the code when the event is raised. These controls compare their current values with previous values, and the previous values are implicitly stored in ViewState if there is any procedure subscription change event. If you disable the ViewState of a control and you are working on a change notification event for that control, the change notification event is not fired correctly because the previous value is always assumed to be the same as the default value of the form.

  ViewState problem

As I pointed out earlier, in asp.net 1 , ViewState has many problems. By default, it is enabled unless you know that it is found and disabled when you do not need to use it, which can significantly increase the amount of data that is rendered by the page. When using a data-bound control, all controls use ViewState to save the state after the postback, which can become extremely painful. As a simple and vivid example, asp.net the page code:

<%@ Page language= "C #"%>
<%@ Import namespace= "System.Data"%>
<%@ Import namespace= "System.Configuration"%>
<%@ Import namespace= "System.Data.SqlClient"%>
<script language= "C #" runat= "Server" >
protected override void OnLoad (EventArgs e)
{
String DSN = configurationsettings.appsettings["Dsnpubs"];
String sql = "SELECT * from Authors";

using (SqlConnection conn = new SqlConnection (DSN))
using (SqlCommand cmd = new SqlCommand (SQL, conn))
{
Conn. Open ();
_DG1. DataSource = cmd. ExecuteReader ();
_DG1. DataBind ();
}
Base. OnLoad (e);
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<asp:datagrid id= "_DG1" runat= "Server"/>
</form>
</body>

This page has a DataGrid control that binds the results of a simple query to the authors table in the pubs database. If you run this page (make the necessary corrections to the connection string) and look at the ViewState field, you may be surprised to find that there are more than 12,000 characters inside. You'll be even more surprised when you look at the content of the page and realize that the actual number of characters required to display the entire table content in the browser is about 1,600. One of the reasons for this is that ViewState not only encodes data, but also encodes data types (metadata), and BASE64 encoding typically increases the overhead of approximately 33 of the space system. Also, a large amount of overhead is just to keep the control state after post requests, which seems disproportionate to time and must do everything possible to avoid it.

Obviously, if you are concerned 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 of spreading ViewState, but never used, which is the primary rule recommended when optimizing the ViewState use of a site: if the content of the control is populated every time the page is requested, it is generally safe (and wise) to disable the control's ViewState.

On the other hand, you may decide to use ViewState to preserve control state, and populate the contents of the control (just through subsequent POST requests) only on the first GET request of the page. This eliminates the round trip for any back-end data source used. By modifying my page to take advantage of this conclusion, I changed the OnLoad method so that it checks the ISPOSTBACK flag before populating the DataGrid, as shown in the following code.

protected override void OnLoad (EventArgs e)
{
if (! IsPostBack)
{
String DSN = configurationsettings.appsettings["Dsnpubs"];
String sql = "SELECT * from Authors";
using (SqlConnection conn = new SqlConnection (DSN))
using (SqlCommand cmd = new SqlCommand (SQL, conn))
{
Conn. Open ();
_DG1. DataSource = cmd. ExecuteReader ();
_DG1. DataBind ();
}
}
Base. OnLoad (e);
}

Of course, there are some other possible better choices, such as caching the server's query results, and rebind the controls each time the request is made. It is up to you to weigh the location of state storage and the importance of specific architectures and applications.

You may notice that I have carefully mentioned that disabling ViewState "General" is safe if the contents of the control are filled every time a page is requested. The exception is that some controls use both ViewState retention behavior and general state. As mentioned earlier, the Drop-down list and text box controls use ViewState to store the previous values to properly publish the change notification events on the server. Similarly, the DataGrid class uses ViewState to publish paging, edit, and sort events. Unfortunately, if you want to use features such as sorting, paging, or editing in the DataGrid, you cannot disable its ViewState. For developers trying to build a fast-working site, the ViewState of the server-side control is not all that is asp.net 1. The server-side control model for x The frustrating side of the other person.

[1] [2] [3] Next page



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.