Use of static variables and viewstate in asp.net (caution) _ Practical Tips

Source: Internet
Author: User

In the development of CS software under the. NET platform, we often encounter the value of some variables last modified, for the sake of simplicity, many people are accustomed to using static to define these variables, so do I. This is very convenient, the next time you call a function, the variable still holds the processed values, directly to use it.

Now it's in the BS software development, and we're naturally going to use that habit. If you count the number of times a button is pressed on a page, first define a static variable time before the processing of the onclick event in the class, and then add a 1 to the call to the button each time the OnClick event is invoked:
[C #]:

Copy Code code as follows:

...
static int times=0;
...
private void Button1_Click (Object Sender,eventargs e)
{
times++;
Label1.text=times. ToString ();
}

When we are glad to be so convenient, we never realize that we have planted a time bomb which is difficult to detect. Why, where?
This also has to start from the operating mechanism of asp.net. In the CS mode software development process, we usually do not care where the application is run, where the variables are stored, the client program is running on the client, server-side programs running on the server side, in general, the two in addition to the data in the database basically no other shared things. So at this point the client's users can safely use static variables, because they are stored in the client program.

So we are accustomed to do in the BS mode of the page is also used static variables, but asp.net in the static is different from the 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 will be affected by the operation of the variable. Take the example of the above counter, assuming that the Times initial value is 0, because at this time only we are using this page, of course, there is no problem, but if there are two people connected to this page at the same time, if a clicked Button1, then B refresh the page after Label1 will display 1, If b Click Button1 once again, then the Times become 2, two people refresh the page after the problem: A and B will say, I clearly only clicked Button1 once, how Label1 show I clicked two times? -That's because two people share the same times on the server, and any person's actions on the times are displayed in the browsers of others who use the page. The problem is here.

What do we do? Fortunately, in addition to the traditional ASP's session object, ASP.net provides a better ViewState object. The ViewState object is used to save various variables, even objects, in the page. Using the method and Hashtable similar, as long as the variable name index, such as viewstate["Var", you can use the access variable var value, regardless of whether Var is a normal variable, or an object, or even a DataTable in memory, too convenient. Why can I use ViewState instead of static variables? The reason is that the server side creates a viewstate for each user who is connected to the page, so the viewstate corresponds to a page-level session. This allows us to safely use ViewState to access the variables and objects that need to be staged.
the use of ViewState is simple, as shown below
1, save the variable to viewstate:
Viewstate["Times"]=times;//store ordinary variable times
viewstate["Orders"]=dtorders;//Storage of DataTable objects Dtorders
2, read out the value of the ViewState:
times= (int) viewstate["Times"];
Dtorders= (DataTable) viewstate["Orders"];
See, huh? It's so simple! Some friends ask why do I have to force type conversion when I read the value of a variable? This is because when a variable (whether an int-type normal variable times or a DataTable-type Object dtorders) is stored in the ViewState, ViewState can be treated as object regardless of whether you are a normal variable or objects. So when we take out what is stored in the ViewState, we must convert it to the appropriate type, otherwise it will be an error. This operation does not need to save the variable with viewstate, the system will automatically convert. (Note that the string in the ViewState bracket is just to identify the index of the different variables, not the same as the variable) so the code for the above counter should be as good as this:
Copy Code code as follows:

...
Viewstate["Times"]=0;
...
private void Button1_Click (Object Sender,eventargs e)
{
int times= (int) viewstate["Times"];
times++;
Viewstate["Times"]=times;
Label1.text=times. ToString ();
}

Generally, it is easier to implement objects (or variables) that will be saved to ViewState in the form of attributes. For the above counter times, this can be handled as follows:
Copy Code code as follows:

...
private int times
{
Get
{
return (int) viewstate[The "Times"];
}
Set
{
Viewstate["Times"]=value;
}
}
...
private void Button1_Click (Object Sender,eventargs e)
{
times++;
Label1.text=times. ToString ();
}
...

Is it convenient to operate as a private property here?
Does that mean static variables are useless? No, of course not! Classes that are declared with static in C # are used directly without instantiation. It is precisely because all users share the same static variable on the server side that a static object can be used to access some common processing modules, such as type conversion, validation of variables, and so on. Therefore, it depends on the specific circumstances.

One more thing to note: If you want to share an object or variable in multiple processes on a page, it's not OK to define a page-level global variable at the beginning of the page class, but the static is OK, but it says this type of variable is unsafe, so you can use ViewState.

OK, so we can rest assured that some variables or objects are temporarily stored.

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.