3

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?

Gavin Miller
  • 43,168
  • 21
  • 122
  • 188
matthewdunnam
  • 1,656
  • 2
  • 19
  • 34

2 Answers2

4

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....
         }
    }
}
Mike Marshall
  • 7,788
  • 4
  • 39
  • 63
  • "our class member variables do not live on once the response is sent to the browser." Put another way: each postback is working with a NEW instance of your page class. – Joel Coehoorn Mar 27 '09 at 16:39
3

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?

Community
  • 1
  • 1
Gavin Miller
  • 43,168
  • 21
  • 122
  • 188