Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Strange behaviour of boolean variable, the value of variable is lost between postback

I have a boolean variable called CheckBoxActivated that I assign to true after validating a user name and password.

string name = us.UserName;
string password = us.Password;

if (name.Equals(txtName.Text) && (password.Equals(txtPassword.Text)))
{
    CheckBoxAvtivated = true;

The strange thing is,after assigning 'true' to the variable I click another button and immediately it becomes 'false' which results in undesired behaviour.

protected void butNext_Click(object sender, EventArgs e)
{
    if (CheckBoxAvtivated)
    {
        pnlCheckBoxes.Visible = true;
        pnlUserCheckBoxValidation.Visible = false;
    }
    else
    {
        pnlCheckBoxes.Visible = false;
        pnlUserCheckBoxValidation.Visible = true;
    }

The state of the variable thus changes to false unexpectedly. Any reason why this could happen?

like image 328
Arianule Avatar asked Jan 31 '13 06:01

Arianule


1 Answers

The class level variables (global variables) in asp.net does not maintain state between postbacks you have to use viewstate if you want to keep the state between postbacks. ASP.NET is based on the HTTP protocol, which is stateless protocol and provides no means of storing a user's data between requests

To set in viewstate

ViewState["CheckBoxAvtivated"] = "true";

To get from viewstate

bool CheckBoxAvtivated = bool.Parse(ViewState["CheckBoxAvtivated"].ToString());

It is important to learn where to use viewstate and where it should not be used.

The Role of View State

View state's purpose in life is simple: it's there to persist state across postbacks. (For an ASP.NET Web page, its state is the property values of the controls that make up its control hierarchy.) This begs the question, "What sort of state needs to be persisted?" To answer that question, let's start by looking at what state doesn't need to be persisted across postbacks. Recall that in the instantiation stage of the page life cycle, the control hierarchy is created and those properties that are specified in the declarative syntax are assigned. Since these declarative properties are automatically reassigned on each postback when the control hierarchy is constructed, there's no need to store these property values in the view state.

From MSDN.

Stateless protocol

In computing, a stateless protocol is a communications protocol that treats each request as an independent transaction that is unrelated to any previous request so that the communication consists of independent pairs of requests and responses. A stateless protocol does not require the server to retain session information or status about each communications partner for the duration of multiple requests. In contrast, a protocol which requires the keeping of internal state is known as a stateful protocol.

From Wikipedia

like image 60
Adil Avatar answered Sep 27 '22 21:09

Adil