Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

c# - variable initialized in class loses its previous value with the page loading

I've declared a String variable test with "hi". every time I click on Button1, I expect that test will be appended with its previous value. But I have noticed that it loses its previous value when the button is clicked and the page is reloaded. That is every time I click it, it has its text as "hihi". I expect "hihihihi" on the next click and so on. What's the problem here with the code below?

public partial class _Default : System.Web.UI.Page
{

    String test = "hi";

    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        test += test;
        Button1.Text = test;
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No, that's not the way asp.net works. If you need that behavior you should do this:

public string test {
  get {
    return (string) ViewState["test"] ?? "hi";
  }
  set {
    ViewState["test"] = value;
  }
}

When ASP.NET sends a request to the server, a new version of your class is instantiated. If you need to get the state, you need to use ViewState (which is saved in a hidden field in the browser and sent with every request, and therefore state saved per page), or you can use SessionState which is a state saved per user. SessionState by default is saved in memory. So, if you restart IIS, this state will go away. Note that viewstate's state will NOT go away if you reset IIS (since it's being sent by the browser). You can also use the Cache which again, is saved in memory. This state is for all users of your application. The same rules about resetting IIS apply. Finally, you could make your variable static. As I said, every time a request is made a new version of your class is instantiated. Of course, static variables are not instance variables, so the state of a static variable is saved across postbacks as well. The same rules about IIS reset apply to static variables as Cache and Session.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...