Tuesday, July 12, 2011

Using client-side state management in Asp.Net

ASP.NET provides several techniques for storing state information on the client. These include the following:

View state: ASP.NET uses view state to track values in controls between page requests. You can also add your own custom values to the view state.

Control state: Control state allows you to persist information about a control that is not part of the view state. This is useful to custom control developers. If view state is disabled for a control or the page, the control state will still function.

Hidden fields: Like view state, HTML hidden fields store data without displaying that data to the user’s browser. This data is presented back to the server and is available when the form is processed.

Cookies: Cookies store a value in the user’s browser that the browser sends with every page request to the same server. Cookies are the best way to store state data that must be available for multiple Web pages on an entire Web site.

Query strings: Query strings are values stored at the end of the URL. These values are visible to the user through his or her browser’s address bar. Use query strings when you want a user to be able to e-mail or instant message state data within a URL.

ViewState: View state is the default mechanism used by ASP.NET to store user-specific request and response data between page requests. The data being stored is typically specific to the controls on the page. View state stores object data that is not already represented as HTML in the page response. This ensures that data set on the server is preserved between round trips to the client and the server.

The Page.ViewState property provides a dictionary object for retaining values between multiple requests for the same page. This object is of the type StateBag. When an ASP.NET page is processed, the current state of the page and its controls is hashed into a string and saved in the page as an HTML hidden field called __ViewState.


Reading and Writing Custom View State Data:
You can use view state to add and retrieve custom values that you need persisted between page requests.

Adding data to the view state is great when you need the information passed back to the server as part of the page post. However, the content of the view state is for that page only. The view state does not transfer from one Web page to another. Therefore, it is useful only for temporarily storing values between requests to a single page.

Eg:
Place a button and write the following code on its click event.

ViewState["a"] = Convert.ToInt32(ViewState["a"]) + 1;
Response.Write("viewstate value = "+ViewState["a"]);


Hidden Fields
Hidden fields in HTML are simply input fields that are embedded in a page’s HTML, not displayed to the user (unless the user chooses to view the page’s source), and then sent back to the server on the page post.

Like view state, hidden fields only store information for a single page. Therefore, they are not useful for storing session data that is used between page requests. Unlike view state, hidden fields have no built-in compression, encryption, hashing, or chunking. Therefore users can view or modify data stored in hidden fields.

Eg: place a HiddenField and set its initial value into zero. Place a button too and write the following on its click event.

HiddenField1.Value = (Convert.ToInt32(HiddenField1.Value) + 1).ToString();
Response.Write("Hidden value = "+HiddenField1.Value);

Cookies : A cookie is a small amount of data that you write to the client to be stored and then passed with requests to your site.

You write persistent cookies to a text file on the client machine. These cookies are meant to survive the user shutting down the browser and reopening it at a later time. You can also write temporary cookies to the memory of the client’s browser. These cookies are used only during the given Web session. They are lost when the browser closes.

Reading and Writing Cookies

Eg:

    protected void btnCreate_Click(object sender, EventArgs e)
{
HttpCookie c = new HttpCookie("mycookie");
c.Value = "Jobin John";
c.Expires = DateTime.Now.AddDays(3);
Response.Cookies.Add(c);
}
protected void btnRead_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["mycookie"];
if (c != null)
{
Response.Write(c.Value);
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["mycookie"];
if (c != null)
{
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);
}
}

Storing Multiple Values in a Cookie: The size of your cookie is dependent on the browser. Each cookie can be up to a maximum of 4 KB in length. In addition, you can typically store up to 20 cookies per site.


protected void btnCreate_Click(object sender, EventArgs e)
{
HttpCookie c = new HttpCookie("mycookie");
c["site"] = "http://www.certifications4you.com/";
c["date"] = DateTime.Now.ToString();
c.Expires = DateTime.Now.AddDays(3);
Response.Cookies.Add(c);
}
protected void btnRead_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["mycookie"];

if (c != null)
{
Response.Write(c["site"]+"<br>"+c["date"]);
}
}
protected void btnDelete_Click(object sender, EventArgs e)
{
HttpCookie c = Request.Cookies["mycookie"];
if (c != null)
{
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);
}
}

Query Strings
Query string values are appended to the end of the page URL. They are set off with a question mark (?) followed by the query string term (or parameter name) followed by an equal sign (=) and the given parameter’s value. You can append multiple query string parameters using the ampersand (&).

Values sent to your page via the query string can be retrieved on the server through the Page.Request.QueryString property

Eg:
Add two Login.aspx and Home asp.x. place three buttons in the
Login.aspx:
Response.Redirect("home.aspx?user="+txtUserName.Text;

string username=Request.QueryString["user"].ToString();
Response.Write(username);

on Home.aspx's page load:
Response.Redirect("home.aspx?user="+txtUserName.Tex+"&pass="+txtPassword.Text);
string username=Request.QueryString["user"].ToString();
string password=Request.QueryString["pass"].ToString();
Response.Write(username+ " " +password);