Static variables on the Asp.net page

Source: Internet
Author: User
Refer. It can be said that all instances of this class share a static variable. The Asp.net page is a class, and we access a page. An instance of this class will be instantiated on the server to respond to our requests. "All instances share a static variable", which means that the static variable on the Asp.net page accessed by all clients is the same variable.

Every time we access the Asp.net page, it is a brand new object, not the object we accessed last time. Therefore, the changes to the variables on the page were not retained during the last page access. When this problem occurs, many beginners intuitively declare this variable as static. During the test, they find that the page status is actually retained.

TestCodeAs follows:

View code

 Public     Partial     Class  _ Default: system. Web. UI. Page
{
Private Static String STR;
Protected Void Page_load ( Object Sender, eventargs E)
{
If ( ! Ispostback)
{
Str = " This is a static variable value assignment. " + Datetime. now;
}
}
Protected Void Button#click ( Object Sender, eventargs E)
{
This . Textbox1.text = STR;
}
}

I used Firefox to open three pages in a row and click the button to display the same value (assign the connection value to IE and then change it)

View code

 Public     Partial     Class  _ Default: system. Web. UI. Page
{
// Private Static string STR;
Protected Void Page_load ( Object Sender, eventargs E)
{
If ( ! Ispostback)
{
// STR = "this is a static variable value assignment" + datetime. now;
Viewstate [ " Key " ] = " This is a static variable value assignment. " + Datetime. now;
}
}
Protected Void Button#click ( Object Sender, eventargs E)
{
This . Textbox1.text = Viewstate [ " Key " ]. Tostring ();
}
}

Changed to 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.