How to use static variables and viewstate in Asp.net (Exercise caution)

Source: Internet
Author: User

In. when developing CS software on the. Net platform, we often encounter the need to use some variable values after the last modification. For the sake of simplicity, many people are used to defining these variables using static, me too. This is very convenient. During the next call to a function, the variable still saves the processed value and can be used directly.

Now we are transferred to BS software development, and we will naturally follow this habit. For example, to count the number of times a button is pressed on the page, define a static variable times before the OnClick event processing in the class. Each time the OnClick event of the button is called, it is very convenient to add 1 to times:
[C #]:

Copy codeThe Code is as follows :...
Static int times = 0;
...
Private void button#click (object sender, EventArgs e)
{
Times ++;
Label1.Text = times. ToString ();
}

We were glad that we were so convenient that we did not realize that we had planted an imperceptible time bomb. Why?
This should also be discussed from the operating mechanism of Asp.net. During software development in CS mode, we usually do not care where the application runs, where the variables are stored, and the client program runs on the client, the server-side program runs on the server side. Generally, the two programs have nothing to share except the data in the database. Therefore, the client users can safely use static variables because they are stored in the client program.

So we are used to using static variables for pages in BS mode. We do not know that static in Asp.net is different from static in CS. The reason is simple because all users in Asp.net will use the same static variable. This means that each user who uses the page performs operations on the variable will affect other users. Take the example of the counter above as an example. Assume that the value of the times initial test is 0, because only we are using this page at this time, of course there will be no problem, but if two people connect to this page at the same time, if A clicks Button1 once, Label1 will display 1 after B refreshes the page. If B clicks Button1 again, times will change to 2. The problem will occur after two people refresh the page: both A and B will say that I have only clicked Button1 once. How can Label1 show where I clicked twice? -- This is because two people share the same times on the server. Any person's operations on times are displayed in others' browsers that use this page. The problem lies here.

What should I do? Fortunately, in addition to Session objects in traditional Asp, Asp.net provides a better ViewState object. ViewState object is used to save various variables on the page, or even objects. The usage method is similar to HashTable. As long as the variable name is used as an index, such as ViewState ["Var"], the value of the variable Var can be accessed, regardless of whether Var is a common variable or an object, even a able in the memory is too convenient. Why can ViewState be used instead of static variables? The reason is that the server creates a ViewState for each user connected to the page, so ViewState is equivalent to a page-level Session. Now we can safely use ViewState to access the variables and objects to be saved.
ViewState is easy to use, as shown below:
1. Save the variable to ViewState:
ViewState ["times"] = times; // stores the common variable times.
ViewState ["Orders"] = dtOrders; // stores dtOrders, A able object.
2. Read the value in ViewState:
Times = (int) ViewState ["times"];
DtOrders = (DataTable) ViewState ["Orders"];
Have you seen it? That's easy! Some may ask why forced type conversion is required when reading the value of a variable? This is because when a variable (whether it is an int-type common variable times or a DataTable object dtOrders) is stored in ViewState, ViewState can be a normal variable or an object, all are treated as objects. So when we extract the things that are stored in ViewState, We must convert them to the corresponding type; otherwise, an error will be reported. This operation does not need to be performed when ViewState is used to save the variable. The system automatically converts the variable. (Note that the string in the ViewState brackets is only used to identify the indexes of different variables and does not need to have the same name as the variables.) Therefore, the code of the counter above should be written as follows:Copy codeThe Code is as follows :...
ViewState ["times"] = 0;
...
Private void button#click (object sender, EventArgs e)
{
Int times = (int) ViewState ["times"];
Times ++;
ViewState ["times"] = times;
Label1.Text = times. ToString ();
}

In general, it is more convenient to implement the object (or variable) to be saved to ViewState in the form of attributes. For the counter times mentioned above, you can handle it like this:Copy codeThe Code is as follows :...
Private int times
{
Get
{
Return (int) ViewState ["times"];
}
Set
{
ViewState ["times"] = value;
}
}
...
Private void button#click (object sender, EventArgs e)
{
Times ++;
Label1.Text = times. ToString ();
}
...

In this case, times is treated as a private property. Is it very convenient?
That's not to say that static variables are useless? Of course not! Classes declared using static in C # are directly used without instantiation. Because all users share the same static variable on the server, they can use static objects to access some common processing modules, such as type conversion and variable verification. So it depends on the specific situation.

Note: If you want to share one object or variable in multiple processes on the page, we cannot define a page-level global variable at the beginning of the page class. static can be used, however, the variables of this type are not safe, so ViewState can be used.

Now we can save some variables or objects with ease.

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.