ASP. NET page status management-Use of viewstate

Source: Internet
Author: User

ASP. NET viewstate is designed to persist the state of objects on the current page, so that the page status can be restored after the next page bounce (PostBack. Note the following two points:

  1. Viewstate is used only on the page where PostBack is required;
  2. Under the premise of 1, only objects whose initial state value is modified need to be persistent, that is, viewstate is used.

1. Let's talk about the 2nd points. Taking a simple label control as an example, let's take a look at its implementation of the text attribute:

Publicvirtualstringtext
{
Get
{
Objectobj2 = This. viewstate ["text"];
If (obj2! = NULL)
{
Return (string) obj2;
}
Returnstring. empty;
}
Set
{
If (this. hascontrols ())
{
This. Controls. Clear ();
}
This. viewstate ["text"] = value;
}
}

Obviously, the backend of the text attribute uses viewstate as the storage medium. Many attributes of the ASP. NET Server-side controls are implemented in a similar way. Assume that a page is default. there is only one label control in Aspx. <asp: Label id = "label1" runat = "server" text = "label"> </ASP: Label>: When you access this page, the Code sent from the label control to the client browser is <span id = "xxx_label1"> label </span>, and a text attribute value is saved in viewstate, the format is probably <input type = "hidden" name = "_ viewstate" id = "_ viewstate" value = "/wepdwukltgwmzg2odmxmq9kfgjmd2qwagidd2qwag ......
Currently, viewstate does not play a role (in the case of viewstate enable). Additionally, the value of the text attribute is redundant. Suppose there is a button control on the page. Click this button to send the page back. Does viewstate play a role in the next process? Analyze the lifecycle of the label control during the page sending back process. First, the label control still needs to go through the initialization phase (init) after sending back. In this phase, you need to create an instance of the label control and set its text attribute at the same time, because the backend of the text attribute uses viewstate as the storage medium, it is equivalent to adding a value to viewstate. Next, the control also needs loadviewstate because it is a sending back process, that is, the status value of the previous access control is loaded. The following shows the implementation of the label control:

protectedoverridevoidLoadViewState(object savedState){if (savedState != null){base.LoadViewState(savedState);stringtext = (string) this.ViewState["Text"];if (text != null){this.Text = text;}}}

In the previous access process, the status value of the text attribute of the label saved in viewstate is the initial value of the label. Therefore, the loadviewsate process is redundant, in addition, both the init and loadviewstate processes assign the same value to the text attribute. It can be seen that even in page sending, if you do not need to modify the initial value of the attribute, the value of the persistent attribute (that is, using viewstate) is meaningless. In addition, excessive resources are wasted, such as assigning values to the text attribute twice and increasing the volume of viewsate.

So, under what circumstances is it worthwhile to use viewsate? Let's take a look at the two access processes in the previous example:

  1. When you access the page for the first time, the label control is initialized and the value of the text attribute is set, that is, an entry is added to viewstate;
  2. Before the page is sent (before render), the control saveviewstate, that is, value serialization in viewsate, is saved to a hidden domain;
  3. Page sending, the label control sends the corresponding HTML Tag, reads the object property value of the HTML Tag set for the text attribute, and sends the hidden domain and its value. For the text attribute of Labe, it is equivalent to sending two client copies for the value in viewstate;
  4. For the second re-access, the label control is initialized and the value of the text attribute is set, that is, an entry is added to viewstate;
  5. In this example, the status value of the text attribute in viewstate is read from the loadviewstate process. The value is actually equal to the value set in process 1, set the text attribute again for the read value,
  6. The second sending, repeat the process 2, 3.

From process 1 control initialization to process 6, saveviewstate before the second sending, in the middle of the two processes, if you do not need to change the initial value of the text attribute, you actually do not need to use viewstate. Suppose we change the text attribute value in the process 1 and 2, as in page_load:

Protected void page_loadt (Object sender, eventargs E)
{
If (! Ispostback)
{
Label1.text = "Change label's value ";
}
}

Therefore, even though the label1.text = "Change label's value" statement cannot be executed during sending back, the value set for the first access is due to viewstate, it will still exist after the second re-sending, that is, the label's text attribute value is "Change label's value" instead of its initial value "label ". In this case, viewstate is useful. Note! Ispostback usage. Otherwise, you only assign values for each access and do not take advantage of viewstate.

Therefore, we can conclude that viewstate should be used only when the preceding two conditions are met. So in real applications, when the above two conditions are met at the same time, that is, when we need to use viewsate?

Obviously, data binding is the biggest condition to meet these two conditions. In my opinion, viewstate is designed to persist necessary information on the page and avoid two accesses, instead, all sending and receiving requests must be bound to data (each data binding usually means database access again and again ). For example, if you bind the datasource control to a gridview to display the data of a class table, in the case of viewsate enable, the data is bound when the page is loaded for the first time, and in subsequent sending and receiving requests, if the current data view is still accessed, that is, no paging or sorting operations are performed, datasource no longer binds data, because all information can be obtained from viewsate, you do not need to re-access the database and re-bind the data control. If you disable viewstate disable, data binding is required for each access (you can use sqlprofiler to capture sqldatasource access to the database in two cases ). This scenario may best demonstrate the original design intention of viewsate.

However, in practical applications, what is the above scenario? On the data list page, there are usually no re-sending operations except paging sorting (do you have a re-sending button in the page where you put the grid ?), For paging and sorting operations, data needs to be rebound for sending back. If this is the case, you should set this page or the enableview attribute of this grid to false. Some people will say that if it is set to false, how will the page information and sorting information of the grid be transmitted to the subsequent sending and receiving requests? In fact, the control state management in ASP. NET 2.0 is divided into two parts: view State and control state. What is the difference between the two? ASP. net 1. in the DataGrid Control of X, all status information of the DataGrid is stored in the view State, but the view State application scenarios that the information conforms to are contradictory. For example, your page does not have a sending back operation, you do not need to cache all the data into the view State. In this case, you will set the enableviewstate attribute of the DataGrid to false. However, after you do this, the DataGrid has other functions such as paging and sorting, it cannot be used because the status information of paging sorting is stored in view State, such as pageindex and sort ASC/DESC. Similar to this problem, control state is introduced in ASP. NET 2.0, and the storage method of control state is the same as that of view State. The difference is that it will not be disable. In this way, the control state is used to store the functional and necessary information of those controls. For example, even if the view state of the gridview is disabled, its paging and sorting information still works normally.

ASP. some designs of net, such as a form element on the entire page and the use of view State mentioned in this article, are aimed at saving costs and improving efficiency in terms of probability statistics. But it is specific to a web application, an application scenario, a page, or even a control. If you know what is behind them, you can implement or use it more correctly.

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.