asp.netwebformsispostback

IsPostBack doesn't work in ASP.NET


I want that when the page is first loaded , the string str is initialized with the text "I am here". And when the page is updated by clicking on the button (btn_click) the value is the same that was initialized. But it does not work. In the console I reads:

First time I load the page: "I ​​am here"

1.When I click on the button: "empty"

2.And I think we should keep this value: "I am here". Please help.

public partial class Default : System.Web.UI.Page
{
    string str = "empty";

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                str = "I am here";
                Debug.Write("VALUE: " + str + "\r\n");
            }

            else
            {
                Debug.Write("VALUE: " + str + "\r\n");
            }
    }

    protected void btn_Click(object sender, EventArgs e)
        {
            //do something...
        }
}

Solution

  • Each individual request to the server creates a new instance of the page... both the very first request (IsPostBack==false) and all subsequent requests (IsPostBack==true).

    This means that your str variable is initialised with "empty" every time you request the page, but only ever set to "I am here" on the first load (i.e. the IsPostBack==false). You need to store it somehow so that when the post-back occurs you still have it.

    There are several ways, including using the Session object, but I would suggest using the ViewState like this...

    string str = "empty";
    
    protected void Page_Load(object sender, EventArgs e)
    {
      if (!Page.IsPostBack)
      {
        str = "I am here";
        ViewState["str"] = str;
        Debug.Write("VALUE: " + str + "\r\n");
      }
      else
      {
        str = (string)ViewState["str"];
        Debug.Write("VALUE: " + str + "\r\n");
      }
    }