Managing states in asp.net

HTTP is a connectionless and thus a stateless protocol. A webrequest just ask for a page and after receiving the page it forgets everything. Still we like to build web-application with HTTP protocol and retain some sort of state. If a user is logged in for example or if a part of a page is hidden or just visible. ASP.net offers for this several solutions:

Statemangement

  • Viewstate
  • Session
  • Query string
  • Cookies

Viewstate

Viewstate is used for retaining state of controls of the same page. It doesn't work for different pages. It's a rule of thumb that variables of the local controls are saved in viewstate and application variables are saved in the session. Example:

public void Page_Load(Object sender, EventArgs e)
{        
	// On postback read the value from the viewstate
	if (IsPostBack)
	{
		if (ViewState["Test"] != null)
            	{
                	lblTest.Text = ViewState["Test"].ToString();
            	}
	}
}
void btnSubmitForm_Click(object sender, EventArgs e)
{
            //on submit form, set the value in the ViewState
            ViewState["Test"].ToString() = lblTest.Text;
}

Session

Query string

Cookies

{{opmerking.Naam}}:

{{opmerking.OpmerkingText}}

            

Saving your comment....

Naam is verplicht!
Email is verplicht!
Opmerking is verplicht!