Asp.net Global Variables

I am writing a page in ASP.NET and I am having problems after the initialization loop during postbacks:

I have (something similar) 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 happens is that my code types “pastString” just fine, but for some reason, when posting back, it is reset to the default value - even if I put the default destination in the Page_Init code ... which makes me wonder what is going on.

Any help?

+3
source share
2 answers

Your class member variables do not live immediately after sending the response to the browser. Instead, try using the Session object:

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....
         }
    }
}
+4
+3

Source: https://habr.com/ru/post/1705475/


All Articles