You are on page 1of 27

State Management In Asp.

Net
Client Side

Introduction
State Management is the process by which we maintain session related information and additional information about the controls and its state. The necessity of state management arises when multiple users request for the same or different Web Pages of a Web Site.

Types Of State Management


There are two types of state management: 1. Server Side Data is stored in memory on the server. It includes application state, session state and profiles. 2. Client Side Data is stored on the client in various ways. It includes cookies, viewstate, query strings and hidden fields.

Types to be covered: 1. Cookies 2. Query Strings. 3. Hidden Field. 4. ViewState 5. Applications 6. Sessions 7. Profiles

Cookies
A cookie is a small text file sent by web server and saved by web browser on client machine. Cookies are also known by many names, HTTP Cookie, Web Cookie, Browser Cookie, Session Cookie, etc. Common use of cookies is to remember users between visits. In each cookie you can not save more than 4k of information.

clients can open cookies and see the content of a cookie so they are not secure. Cookies are usually used to save user preference information. Size of cookies is limited to 4096 bytes. Total 20 cookies can be used on a single website; if you exceed this browser will delete older cookies. End user can stop accepting cookies by browsers, so it is recommended to check the users state and prompt the user to enable cookies.

Types OF Cookies
There are 2 different types of cookies: 1. PERSISTANT COOKIES: A persistent cookie is one stored as a file on your computer, and it remains there when you close Internet Explorer. 2. TEMPORARY(SESSION) COOKIES: A temporary or session cookie is stored only for your current browsing session, and is deleted from your computer when you close your browser.

Example 1: Creating Cookies(Using HttpCookie Class): Take a new website and make design page as shown in the next slide. Do coding on login button click as shown below:

Coding on login button click: protected void Button1_Click(object sender, EventArgs e) { HttpCookie mycookie = new HttpCookie("cookie1"); mycookie["Name"] = TextBox1.Text; mycookie["password"] = TextBox2.Text; Response.Cookies.Add(mycookie); mycookie.Expires = DateTime.Now.AddDays(1); Response.Redirect("home.aspx"); }

Make another page as home.aspx and do coding on page load as shown: protected void Page_Load(object sender, EventArgs e) { HttpCookie reqcookie = Request.Cookies["cookie1"]; if (reqcookie != null) { Label1.Text = reqcookie["Name"]; Label2.Text = reqcookie["Password"]; } }

Example: Create Cookies( Using Response) Take a textbox and a button. On button click, do coking as: protected void Button1_Click(object sender, EventArgs e) { Response.Cookies["StudentCookies"].Value = TextBox1.Text; Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1); Response.Redirect("home.aspx"); }

On home page, on page load, do coding as: TextBox1.Text = Request.Cookies["StudentCookies"].Value;

Using Multi Valued Cookies


You can also store multiple name-value pairs in a single cookie. The name-value pairs are referred to as subkeys. A cookie with subkeys also helps you limit the size of cookie files.

Example 3: Take a button and do coding as follows: protected void Button1_Click(object sender, EventArgs e) { Response.Cookies["StudentCookies"]["RollNumber"] = "12"; Response.Cookies["StudentCookies"]["FirstName"] = "Abhimanyu"; Response.Cookies["StudentCookies"]["MiddleName"] = "Kumar"; Response.Cookies["StudentCookies"]["LastName"] = "Vatsa"; Response.Cookies["StudentCookies"]["TotalMarks"] = "499"; Response.Cookies["StudentCookies"].Expires = DateTime.Now.AddDays(1); Response.Redirect("home2.aspx"); }

Take another page as home2.aspx and do coding on page load as: protected void Page_Load(object sender, EventArgs e) { string roll; roll = Request.Cookies["StudentCookies"]["RollNumber"]; roll = roll + " " + Request.Cookies["StudentCookies"]["FirstName"]; roll = roll + " " + Request.Cookies["StudentCookies"]["MiddleName"]; roll = roll + " " + Request.Cookies["StudentCookies"]["LastName"]; roll = roll + " " + Request.Cookies["StudentCookies"]["TotalMarks"]; Label1.Text = roll; }

Query Strings In Asp.Net


A query string is information that is appended to the end of a page URL. Example: http://www.contoso.com/listwidgets.aspx?cat egory=basic&price=100 In the URL path above, the query string starts with a question mark (?) and includes two attribute/value pairs, one called "category" and the other called "price."

Query strings provide a simple but limited way to maintain state information. some browsers and client devices impose a 2083-character limit on the length of the URL.

Example: protected void Button1_Click(object sender, EventArgs e) { int recordid = 10; Response.Redirect("Default2.aspx?recordid=" + recordid.ToString()); } Get the value in the same or another page. string id= Request.QueryString["recordid"];

Hidden Feilds
A HiddenField control stores a single variable in its Value property and must be explicitly added to the page. The information in a HiddenField control is not dis it can be read and set in client script. played when the browser renders the page. Example: <asp:hiddenfield id="ExampleHiddenField" value="Example Value" runat="server"/>

ViewState Controls
The ViewState property provides a dictionary object for retaining values between multiple requests for the same page. When the page is processed, the current state of the page and controls is hashed into a string and saved in the page as a hidden field, or multiple hidden fields if the amount of data stored in the ViewState property exceeds the specified value in the MaxPageStateFieldLength property.

Make a login application in which user is given 3 chances to login: Code: int counter = 3; SqlConnection con = new SqlConnection(); protected void Page_Load(object sender, EventArgs e) { con.ConnectionString = ConfigurationManager.ConnectionStrings["cn"].Connection String; if (con.State == ConnectionState.Closed) { con.Open(); }

if (!Page.IsPostBack) { Label2.Text = counter.ToString(); ViewState["count"] = counter; } protected void Button1_Click(object sender, EventArgs e) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "select password from Table1 where name=@sname"; cmd.Connection = con; cmd.Parameters.Add("@sname", SqlDbType.VarChar,50).Value = TextBox1.Text;

SqlDataReader dr1 = cmd.ExecuteReader(); if (dr1.HasRows) { dr1.Read(); if (TextBox2.Text == dr1["password"].ToString()) { Label1.Text = "you are successfully login"; } else { int i = (int)ViewState["count"]; i = i - 1; ViewState["count"] = i;

if (i > 0) { Label1.Text = "retry ...you have " + i + "chances left now"; } else { Response.Redirect("user.aspx"); } } } dr1.Close(); cmd.Dispose(); //dr.Close();

Comparison
1. ViewState can be applied to all data types of asp.net QueryStrings are limited to string data type. Cookies are limited to string types. 2. ViewState values are stored in hidden fields. Querystring in browsers url. Cookies in clients computer.

3. ViewState lifetime is permanent. Querystrings are lost when the user enters a new url or closes the browser. Cookies lifetime are set by programmers. 4. Scope of viewstate is limited to current page. Scope of querystrings are is limited to the target page. Scope of the cookies are limited to the entire application.

You might also like