Virtual Classes Logo          Virtual Classes
    Read Anytime,Anywhere

Client Side State Management

In client side statement management technique the information either stored on client machine or in page. Client side state management does not use any server resource. The information stored on client machine or in page sent to server along with the request every time the page is posted back to server.
Client side state management technique are-
1-View State : By default, the ASP.NET page framework uses view state to preserve page and control values between round trips. View State is the method to preserve the Value of the Page and Controls between round trips.It is a page level state management technique. When the HTML for the page is rendered, the current state of the page and values of controls those must be retained during postback are serialized into base64-encoded strings and put into hidden fields in the page.Because view state is set in a hidden field, you can make changes to view state, this creates a potential security issue. you can make changes to view state till the page's PreRenderComplete event. If you want to trace your view state information, you can trace it by just enable "Trace" option of Page Directive You can set and can access view state data in your code by using the page's ViewState property. The ViewState property is a dictionary that contains key/value pairs that contain the view state data. Example-
To add data to view state : ViewState["Data"]=data;
To get data from view state : DataType data=(DataType) ViewState["Data"]
To use the ViewState property, the ASP.NET Web page must have a form element that has the attribute runat="server".
You can store objects of the following types in view state:
Strings,Integers, Boolean values,Array objects, ArrayList objects,Hash tables and serilizable objects
View State is turned on by default,but you can change the default behavior of view state and also you can store view state in another location such as a SQL Server database by implementing a custom PageStatePersister class to store page data. View state is enabled by default, this sometimes creates performance issue due to page size. Some controls on a page might not need view state,you can configure controls so that view state is disabled by default for all controls within a page or a container control, and you can then enable view state for specific controls. You can also configure controls so that view state is disabled and cannot be enabled for child controls. To disable view state for a control by default so that it can be enabled for child controls, set the ViewStateMode property of the control to Disabled.
To disable view state by default for an entire page, set the ViewStateMode attribute of the @ Page directive to Disabled.
To disable view state for a control and its children so that it cannot be enabled for child controls, set the EnableViewState property of the control to false. To disable view state for an entire page and all of its child controls, set the EnableViewState attribute of the @ Page directive to false. Even when you explicitly turn view state off, a hidden field is still sent to the browser to indicate that postback is occurring for the page.

2-Control State :Control State was introduced in ASP.NET 2.0 as an alternative to View State as a option for preserving the state of a control. The control state is a way to save a control’s state information when the view is turn off(view state is turn off by setting EnableViewState property). Control State is used to store a control’s essential data only that needs to be available on a page postback. Unlike ViewState a developer can’t turn off control state. The control state can be implemented only in controls that you implement. Implementation of Control state is easy. First, override the OnInit method of the control and add the call for the Page.RegisterRequiresControlState method with the instance of the control to register. Then, override the LoadControlState and SaveControlState in order to save the required state information. The limitation of the control state is that it takes away the choice to disable ViewState. You should only use it whenever you have to keep a state information that without it your control won’t work.
3-Hidden fields : The HiddenField control is used to store a value that needs to be persist across postback to the server. Use value property of to set HiddenField control's value. Because the value of a HiddenField is rendered to the client browser, it is not suitable for storing sensitive values.
The information in a HiddenField control is not displayed when the browser renders the page. However,it can be read and set in client script. Hidden field is suitable in scenario where view state is completely disabled but still we want to maintain some information for the current page. The value of a HiddenField control can be changed before the page is posted back to the server. This might occur because you are using the hidden field to share information between server code and client script, and client script has updated the value of the control. To help you detect changes to data in the control, the HiddenField control raises a ValueChanged event if the value of the control changes between postbacks. You can handle this event to determine whether a value has changed.

4-Cookies :A cookie is a small text file that the server stores on the user's computer.A cookie is often used to identify a user,it is sent by web server and saved by web browser on client machine. Each time the computer requests a page, it sends the cookie with the request object to the server .
For example, when a user visits your site, you can use cookies to store user information for ex. his preferences etc. and when the user visits your site another time, the application can retrieve the information it stored earlier.
Adding data to cookies-
Response.Cookies["UserName"].Value = "VirtualClasses";
Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(1);
HttpCookie cookie = new HttpCookie("UserName");
cookie.Value = DateTime.Now.ToString();
cookie.Expires = DateTime.Now.AddDays(1);
HttpCookie class has below properties-
Name: It contains the name of the cookie.
Value: It contains the value of the cookie.
Expires: It contains the expiration date time of the cookie.
Domain: It contains the domain of the cookie.
HasKeys: It contains True if the cookie has subkeys.
Path: It contains the virtual path to submit with the cookie.
Secure: It contains True if the cookie is to be passed in a secure connection only.
While creating a cookie, you specify a Name and Value,each cookie must have a unique name so that it can be identified later when reading it from the browser. Because cookies are stored by name, naming two cookies the same will cause one to be overwritten.
Before trying to get the value of a cookie, you should make sure that the cookie exists else you will get a NullReferenceException exception.
The browser is responsible for managing cookies,you can read the name and value of a cookie,but you cannot read the cookie's expiration date and time. When the browser sends cookie information to the server, it does not include the expiration information in request object. If you are concerned about the expiration date of a cookie, you must reset it.
By default, ASP.NET uses a non-persistent cookie to store the session state. However, if a user has disabled cookies on the browser, session state information cannot be stored in a cookie. ASP.NET has provided an alternative way to store session information by using cookieless sessions .By cookies less session you can configure your application to store session ID in the URLs of pages in your site rather then in a cookie. Expired cookies are deleted by the browser when a user visits the site that has written the cookies. The expiration of a cookie should be set for as long as your application considers the cookie value to be valid. If you want a cookie that will not expire, you can set the expiration date to any future years from now. Users can delete the cookies on their computer at any time,even if you store cookies with long expiration times. If you do not set the cookie's expiration, the cookie is created but it is not stored on the user's hard disk. Instead, the cookie is maintained as part of the user's session information. When the user closes the browser, the cookie is discarded. You can set a cookie property that causes the cookie to be transmitted only if the connection uses the Secure Sockets Layer (SSL). SSL does not protect the cookie from being read or manipulated while it is on the user's computer, but it does prevent the cookie from being read while in transit because the cookie is encrypted.
You cannot directly modify a cookie,but if you want to change a cookie, create a new cookie with new values and then send the cookie to the browser to overwrite the old cookie on the client machine. the same way you cannot directly remove a cookie because the cookie is on the user's computer,but to delete a cookie you can set the cookie's expiration to any date earlier than today. When the browser checks the cookie's expiration, the browser will discard the now-outdated cookie.
Cookies has some limitation-
1-Most browsers support cookies of up to 4096 bytes. Because of this small limit, cookies are best used to store small amounts of data.
2-Browsers also limits that how many cookies your site can store on the user's computer. Most browsers allow only 20 cookies per site. if you try to store more, the oldest cookies will be discarded. Some browsers also put an absolute limit, which is generally 300, on the number of cookies they will accept from all sites combined.
3-A cookie limitation that you might encounter is that users can set their browser to refuse cookies.
4-You should never store sensitive data in a cookie, such as user names, passwords, credit card numbers, and so on. Do not use cookies to support critical features.

5-Query strings : Often you come across a situation where you need to pass values between your pages.
For example in first page you collect information about logged in user,logged in user name etc. and use this information in your second page.
ASP.NET has provided several options for this and QueryString is one option where we pass the value using property of Request Object. Passing values to different pages using query string is easy,the HTTP query string is specified by the values following the question mark (?).
Below example shows the use of query string-
HTML Code- HREF="WelcomeGuest.aspx?Name="+NewUser
C# Code- Response.Redirect("WelcomeGuest.aspx?Name=" +txtName.Text);

Here we are getting the user name in first page and passing the name of second page which is welcomeGuest page.
QueryString is key value pair collection. In our example Name is the key and and txtName.Text is the value.
Below line show to fetch the value of query string.
Syntax- Request.QueryString(variable)[(index)|.Count]
variable:Specifies the name of the variable in the HTTP query string to retrieve.
index:An optional parameter that enables you to retrieve one of multiple values for variable. It can be any integer value in the range 1 to Request.QueryString(variable).Count. The value of Request.QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request.QueryString(parameter).Count.
txtGuestName.Text = Request.QueryString["Name"];
You can also retrieve this values using their position in the querystring.
txtGuestName.Text = Request.QueryString[0];
As you can see in above code, you can fetch the value of query string using index, if there are multiple values in querystring property. you can fetch the value by using below lines of code also.
foreach( string name in Request.QueryString)

Limitation of using query string-
1-QueryString have a max length,So this approach is not good if you want to send lot of information.
2-Query strings are contained in request headers so QueryString is visible in your address part of your browser so it is not wise to use query string to pass sensitive information.
3-QueryString can not be used to send & and space characters.