Subscribe

RSS Feed (xml)

Storing Information Between Postbacsk

ASP.NET is a stateless programming model. Every time a postback is triggered, your code loads into memory, executes, and is released from memory. If you want to keep track of information after your code has finished processing, you must use some form of state management.

ASP.NET provides several ways to store information, or state, between requests. The type of state you use determines how long the information will live, where it will be stored, and how secure it will be. The below table lists the various state options provided by ASP.NET. This table doesn't include the Cache object, which provides temporary storage and is described in the previous post. You can also use other, custom, approaches, such as hidden fields or a back-end database.

Table : Types of State Management

Type of State

Allowed Data

Storage Location

Lifetime

Security

View State

All serializable .NET data types.

A hidden field in the current Web page.

Lost when the user navigates to another page.

By default, it's insecure. However, you can use page directives to enforce encryption and hashing to prevent data tampering.

Query String

String data only.

The browser's URL string.

Lost when the user enters a new URL or closes the browser. However, it can be stored in a bookmark.

Clearly visible and easy for the user to modify.

Session State

All serializable .NET data types.

Server memory (can optionally be configured for an external process or database).

Times out after a predefined period (usually 20 minutes, but this period can be altered globally or programmatically).

Secure because data is never transmitted to the client.

Custom Cookies

String data only.

The client's computer (in memory or a small text file, depending on its lifetime settings).

Set by the programmer. Can be used in multiple pages and can persist between visits.

Insecure, and it can be modified by the user.

Application State

All serializable .NET data types.

Server memory.

The lifetime of the application (typically, until the server is rebooted). Unlike other methods, application data is global to all users.

Secure because data is never transmitted to the client.

The syntax for different data-storing methods is similar. Data is stored in a collection object and indexed using a string name.

The below figurehows a Web page that performs a test of several different forms of session state. When the user clicks the Store Data button, a new System.DateTime object is created and stored in page view state, session state, and a custom cookie. When the user clicks the Get Data button, this information is retrieved and displayed. Finally, the Clear Data button removes information from all types of state.

aspform.JPG

Here's the page code:


using System;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.SessionState;

public class TestState : System.Web.UI.Page {

protected System.Web.UI.WebControls.Button cmdClear;
protected System.Web.UI.WebControls.Button cmdStore;
protected System.Web.UI.WebControls.Button cmdGetData;
protected System.Web.UI.WebControls.Label lblData;

// (Designer code omitted.)

private void cmdStore_Click(object sender, System.EventArgs e) {

// Create a test object.
DateTime now = DateTime.Now;

// Store the object in view state.
ViewState["TestData"] = now;

// Store the object in session state.
Session["TestData"] = now;

// Store the object in a cookie.
// Check if the cookie already exists (named Recipe07-02).
if (Request.Cookies["Recipe07-02"] == null) {

// Create the cookie.
HttpCookie cookie = new HttpCookie("Recipe07-02");

// The cookie can only store string data.
// It can store multiple values, each with a different key.
cookie["TestData"] = now.ToString();

// (You can modify additional Cookie properties to change
//  the expiry date.)

// Attach the cookie to the response.
// It will be submitted with all future requests to this site
// until it expires.
Response.Cookies.Add(cookie);
}
}

private void cmdGetData_Click(object sender, System.EventArgs e) {

lblData.Text = "";

// Check for information in view state.
if (ViewState["TestData"] != null) {

DateTime data = (DateTime)ViewState["TestData"];
lblData.Text += "<b>View state data:</b> " +
data.ToString() + "<br>";

}else {

lblData.Text += "No view state data found.<br>";
}

// Check for information in session state.
if (Session["TestData"] != null) {

DateTime data = (DateTime)Session["TestData"];
lblData.Text += "<b>Session state data:</b> " +
data.ToString() + "<br>";

}else {

lblData.Text += "No session data found.<br>";
}

// Check for information in a custom cookie.
HttpCookie cookie = Request.Cookies["Recipe07-02"];
if (cookie != null) {

string cookieData = (string)cookie["TestData"];
lblData.Text += "<b>Cookie data:</b> " +
cookieData + "<br>";

}else {

lblData.Text += "No cookie data found.<br>";
}
}

private void cmdClear_Click(object sender, System.EventArgs e) {

ViewState["TestData"] = null;
Session["TestData"] = null;
// (You can also use Session.Abandon to clear all session
//  information.)

// To clear a cookie you must replace it with
// a cookie that has an expiration date that has already passed.
HttpCookie cookie = new HttpCookie("Recipe07-02");
cookie.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(cookie);
}
}

One type of state that this page doesn't demonstrate is the query string. The query string requires a page redirect and is ideal for transferring information from one page to another. To set information, you must redirect the user to a new page and add the query string arguments to the end of the URL. You can use the HttpServerUtility.UrlEncode and UrlDecode methods to ensure the string data is URL legal. This method properly escapes any special characters.

DateTime now = DateTime.Now;
string data = Server.UrlEncode(now.ToString());
Response.Redirect("newPage.aspx?TestData=" + data);

To retrieve this information, you can use the HttpResponse.QueryString collection:


// Check for information in the query string.
if (Request.QueryString["TestData"] != null) {

string data = Request.QueryString["TestData"];
data = Server.UrlDecode(data);
lblData.Text += "<b>Found query string data:</b> " + data + "<br>";
}

No comments:

Variety in the Web World