Webform Application Pass Value ViewState

Source: Internet
Author: User

Application: All sessions share a application space, and anyone who changes the content of application will find it changed. Content in application is not automatically released

Storage location: Service side
All access users are access to the same variable

(1) Application value: application["key Name"] = value; Value, which is not just a string, it can be an object.

        string s = TextBox1.Text;        Application["AAA"] = s;

(2) Application value: Type variable name = (cast type name) application["key Name"]

protected void Page_Load (object sender, EventArgs e)    {        if (application["AAA"]!=null)        {            label1.text= ( String) application["AAA"];           Label1.Text = application["AAA"]. ToString ();        }    }

(3) Determine if a value exists in the application
if (application["key Name"] = = null)
{

}
(4) Release application:application["Key name"] = NULL;

Case: Each access page will accumulate the number of visits

protected void Page_Load (object sender, EventArgs e)    {        if (application["count"] = = null)        {            application ["count"] = 0;        }        application["Count"] = (int) application["Count"] + 1;        Label1.Text = application["Count"]. ToString ();    }
Hidden states-viewstate Quest 1.1 from the stateless state of HTTP

HTTP is a stateless protocol that does not understand the two successive requests of the same session, which are parsed by the newly instantiated environment, which does not save any information about the session, except that the app itself may have been stored in the global object. In addition, because the browser and the server communicate through the socket , the HTTP request usually closes the socket connection, so the HTTP protocol will not remain connected . Maintaining a connection slows down the number of concurrent processing requests by the client, does not maintain a connection, and slows processing (the time required to establish a connection is a little longer);

PS: Here we can understand: if we go to a large shopping mall to buy a product, the first time to go is a salesman received us, led us to the XX products counter and recommended XX products for us; After we go back to use XX products, I feel xx products really good. The second time we went, but this time we can not find the last one salesman, instead of the mall assigned another B salesman to receive us, he did not know that we last chose XX products, instead it is kept to us to recommend YY products and bring us to YY products counter; this time, we will generally say: I rub, the last sister to call me!

Based on the stateless nature of the HTTP protocol, we often encounter this situation in the development of ASP: The last time the user commits something, the server will not remember the next time it is submitted. Many times, we feel very puzzled? Later, we found that each time the request server opened a different thread to handle, that is, each time a new XXX.aspx.cs class object instance to handle (the last time new came out for us to handle the Page object may have been destroyed by the server already). For example, we write a number member of type int (initial 0) in the Xxx.aspx.cs code, and each request we want to increment the number and return it back to the browser. But it is such a simple dream, we can not easily achieve.

So, how do you break it? The great gods have thought for us. We can use hidden field fields, cookies, sessions, and so on to save the state. And great Microsoft has helped us encapsulate ViewStatein ASP, so that when we do postback operations in WebForm, we don't feel that the server is stateless.

1.2 Youth bloom everywhere-the ubiquitous ViewState

(1) A data structure similar to dictionary

If you've ever used dictionary or a session, you should understand the KEY/VALUE data structure. There is no advanced theory, viewstate is indexed by string type data. The values in the ViewState counterpart can store any type of value (the argument is of type Object), and the implementation of any type of value stored in the ViewState will be boxed into the object type.

For example, here we can rewrite the code in the button event above:

View Code

Here, we use ViewState to store the state value of age, the first time I return you 1, I will add 1 back to you. So, the problem we mentioned in the previous section (Unable to remember the last number value, returned 1 each time) was resolved.

PS: ViewState cannot store all data types, only the following are supported:
String, Integer, Boolean, Array, ArrayList, Hashtable, and some custom types

As we all know, dictionary and session are stored on the server side. So, we can not help but ask, since we add a key/value to viewstate on the server side, and return to the browser side, whereis viewstate stored?

(2) Big faint in the city " page level " hidden field

Unlike the session and dictionary storage location,the scope of ViewState is the page , that is, viewstate is stored in the browser's page (here, compared to the session, Consuming less server resources is one of the advantages of viewstate, and when you close an ASPX file, the viewstate that belong to this ASPX will not exist. Perhaps, so we do not know very well, now we come to the field to see.

① First, if there is a form on the page that runat= "server", when the user requests this page, the server automatically adds a _viewstate hidden field to the browser. However, we find that this viewstate value looks like a string of garbled characters? What is this for? This is because the server before returning HTML to the browser, the contents of the ViewState in the Base64 encryption encoding ;

② second, when the user clicks on a button in the page to submit the form, the browser will also submit the hidden domain of the _viewstate to the server, which will be populated into the ViewState attribute when the client parses the request, and the viewstate that the browser submits is deserialized , we can decode the _viewstate by a software as shown in the tree structure, and then according to the business process needs, from this attribute to find the specific value of value and operation of the index, after the operation is completed, The viewstate is then BASE64 encoded again back to the browser side;

③ Therefore, we can draw a conclusion:viewstate is suitable for the same page to interact with the server multiple times (PostBack) without closing. Here we can also review the process of ViewState,viewstate storage "accident Scene", the next can be conveniently "restore the scene", the stateless HTTP simulation into a stateful , but also let the vast number of beginners to understand the non-state of this feature.

1.3 Likes will be presumptuous-love and hate viewstate!

In fact, in addition to the K/V data we manually add to the ViewState property on the server side, we set the values for some server controls in Aspx.cs code (for example, set the dataset that was stored in datasource for Repeater, The text content set for the label, etc., but not including: TextBox, CheckBox, CheckBoxList, RadioButtonList) are stored in the viewstate. In doing so, the next time we submit a request to the server, all the server control states in the existing form are recorded in the ViewState submission to the server, and the server side can conveniently perform stateful operations on these server controls and return it, which is undoubtedly a delight to us, Because of the convenience of our development process, improve our development efficiency;

  but someone said: "Like will be presumptuous", ViewState let people love and hate ah . For example, in the process of using Repeater, WebForm automatically stores datasource (the data source, which you can interpret as a collection) into ViewState and returns it to the browser. Consider the following example to understand the field:

① contains the Repeater aspx page:

View Code

② Background Code simulation gets a dataset from the database merged into the repeater:

View Code

After compiling the build, you can see a long list of _viewstate hidden fields by looking at the HTML code of this page. By copying this _viewstate to Viewstatedecoder, you can see that it does store the collection of data in repeater. Here we ask: since the presentation data has been rendered HTML, why should it be stored in the ViewState hidden domain? If our data collection is 100 rows, 1000 rows of data, then viewstate hidden domain is not very large (100k?200k?)? Unfortunately, this is the design mechanism of viewstate, and to rely on it to maintain state, it will store the state of the server control, including the data collection, and pass the hold state back and forth between the browser and the server.

Here is the discussion about the performance of the website: Because viewstate is stored in the page itself, if you store a large value, the user requests that the page be displayed slower (which is a nightmare for Internet systems.) would you choose a Web browser that responds within 1 seconds or a Web site that responds within 5 seconds? ). And because ViewState will accompany form table single back to the server, if the viewstate is very large, the HTTP message will be very large, the website traffic consumption will increase.

So, is there a way to viewstate restraint? Don't worry, please see the introduction below.

1.4 But love is restraint-disable or can't help using ViewState?

Just said, because ViewState will affect performance to some extent, so we can disable ViewState when we don't needit. By default, ViewState is enabled and is determined by each control (not the page developer) to determine what is stored in ViewState. Sometimes, this information is of little use to the application (for example, the repeater data set mentioned above, the rendered HTML display is generated, and a copy is stored in viewstate). Although it is 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 . Of course, ViewState helps us achieve some server control state retention, so it can be used moderately if not required, especially in the context of developing an enterprise's internal information system.

So, how to disable viewstate? What's the strategy for disabling viewstate? Below we hit discuss.

① page-level disabled ViewState: Add enableviewstate= "false"to the page instruction set in the header of the ASPX, the state of all the controls in the pages will not be stored in ViewState, and the page will be refreshed a lot;

<%@ page language= "C #" autoeventwireup= "true" codebehind= "RepeaterViewState.aspx.cs"    inherits= " Webformdemo.repeaterviewstate "enableviewstate=" false "%>

Once disabled, once again look at the generated HTML code, we will find: Gee,_viewstate still there, but significantly smaller than the previous volume of a lot !

Then copy this thin _viewstate into the viewstatedecoder to do the anti-coding view, we will find that only one of the most basic information, repeater of those data collection is not stored in.

PS: Why is there still _viewstate hidden field in the page source code after disabling viewstate?

This is because even if the viewstate,aspx page is disabled, a server control is used there, which is <form runat= "Server" >. At this point, if you remove the form runat= "Server" and turn it into a normal HTML tag, then the page will be clean, and _viewstate this hidden field completely disappears in your page.

② Control-level disable ViewState: In some scenarios, we only want to disable the viewstate of a control (for example, Repater), and other controls remain state through ViewState. At this point, we can set a property enableviewstate= "false" for the specified control;

<asp:repeater id= "repeaterproducts" runat= "Server" enableviewstate= "false" ></asp:Repeater>

③ global level Disable ViewState: The great God of the garden, Jeffrey Zhao, once said, "If I create a new WebForm project, The first thing to do is to go to the Web. config and set EnableViewState to False to turn viewstate global off. So, if we want to viewstate all the pages in the site are disabled, it is not possible to go to a page to modify page instructions? Asp. NET provides us with a configuration, we only need to add a configuration to the system.web of Web. config:

<pages enableviewstate= "false"/>

PS: The development can also be used in the practice of the old Zhao, first disabled, and then selective activation, after all, there is no need to ViewState to do the thing!

④ true Disable ViewState: Just after our three methods have been practiced, the page still appears in the hidden field of _viewstate, although it retains the most basic information. So, we might ask? How to completely disable ViewState, do not give me to generate _viewstate hidden domain. The answer is, will <form runat= "server"/> runat= "Server" removed, will not appear, but that will deviate from the WebForm development mode, most of the server controls are not working properly, development efficiency will be lost.

To sum up, in the actual development should weigh the pros and cons, special circumstances special analysis (in the end this scenario should not disable ViewState), choose whether to disable ViewState, the way to disable viewstate. For the viewstate of the mystery of this article to this end, because I personally understand is not very deep, so I hope that if you have the understanding of the park, you can reply to discuss common progress.

Webform Application Pass Value ViewState

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.