Asp.net “Global” variables

前端 未结 2 1348
终归单人心
终归单人心 2020-12-21 06:20

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:

p         


        
相关标签:
2条回答
  • 2020-12-21 07:14

    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....
             }
        }
    }
    
    0 讨论(0)
  • 2020-12-21 07:16

    I feel your pain Matt. I asked a similar question a little while ago:

    For a further understanding of the Page Life Cycle check out this question: What is the 'page lifecycle' of an ASP.NET WebForm?

    0 讨论(0)
提交回复
热议问题