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
775 views
in Technique[技术] by (71.8m points)

.net - Asp.net "Global" variables

I'm writing a page in ASP.NET and am having problems following the cycle of initialization on postbacks:

I have (something akin to) the following:

public partial class MyClass : System.Web.UI.Page
{
    String myString = "default";

    protected void Page_Init(object o, EventArgs e)
    {
        myString = Request["passedString"];
        //note that I've tried to set the default here in Init on NULL...
    }

    protected void Page_Load(object o, EventArgs e)
    {
         if(!Postback)
         {
             //code that uses myString....
         }
         else
         {
            //more code that uses myString....
         }
    }
}

And what's happening is that my code picks up the "passedString" just fine, but for some reason, on postback, it resets to the default value - even if I put the assignment of the default in the Page_Init code... which makes me wonder what's going on..

Any help?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Your class member variables do not live on once the response is sent to the browser. Try using the Session object instead:

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

    protected void Page_Init(object o, EventArgs e)
    {
        Session["myString"] = Request["passedString"];
        //note that I've tried to set the default here in Init on NULL...
    }

    protected void Page_Load(object o, EventArgs e)
    {
         string myString = (string) Session["myString"];

         if(!Postback)
         {
             // use myString retrieved from session here
         }
         else
         {
            //more code that uses myString....
         }
    }
}

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

...