View State
View State is one of the most important and useful client side state management mechanism. It can store the page value at the time of post back (Sending and Receiving information from Server) of your page. ASP.NET pages provide the ViewState property as a built-in structure for automatically storing values between multiple requests for the same page.
Example:
If you want to add one variable in View State,
ViewState["Var"]=Count;
For Retrieving information from View State
string Test=ViewState["TestVal"];
Advantages of view state?
This are the main advantage of using View State:
* Easy to implement.
* No server resources are required.
* Enhanced security features ,like it can be encoded and compressed.
Disadvantages of view state
It can be performance overhead if we are going to store larger amount of data, because it is associated with page only. Its stored in a hidden filed in hashed format still it can be easily trapped. It does not have any support on mobile devices.
When we should avoid view state?
You won’t need view state for a control for following cases,
* The control never change
* The control is repopulated on every postback
* The control is an input control and it changes only of user actions.
Where is view state stored?
View State stored the value of page controls as a string which is hashed and encoded in some hashing and encoding technology. It only contain information about page and its controls. Its does not have any interaction with server. It stays along with the page in the Client browser. View State use Hidden field to store its information in a encoding format.
Enabling and Disabling View State
You can enable and disable View state for a single control as well as at page level also. To turnoff view state for a single control , set EnableViewState Property of that control to false. e.g.:
TextBox1.EnableViewState =false;
To turnoff the view state of entire page, we need to set EnableViewState to false of Page Directive as shown bellow.
Page Language=”C#” EnableViewState=”false”
Even you disable view state for the entire page , you will see the hidden view state tag with a small amount of information, ASP.NET always store the controls hierarchy for the page at minimum , even if view state is disabled.
For enabling the same, you have to use the same property just set them as True, as for example, for a single control we can enabled view state in following way,
TextBox1.EnableViewState =true;
and for a page level,
Page Language=”C#” EnableViewState=”true”
How to make view state secure?
Many of ASP.NET Programmers assume that this is an Encrypted format, but I am saying it again, that this is not a encrypted string. It can be break easily. To make your view state secure, There are two option for that,
First, you can make sure that the view state information is tamper-proof by using “hash code”. You can do this by adding “EnableViewStateMAC=true” with your page directive. MAC Stands for “Message Authentication Code”
Page Language=”C#” EnableViewState=”true” EnableViewStateMac=”true”
A hash code , is a cryptographically strong checksum, which is calculated by ASP.NET and its added with the view state content and stored in hidden filed. At the time of next post back, the checksum data again verified , if there are some mismatch, Post back will be rejected. we can set this property to web.config file also.
Second option is to set ViewStateEncryptionMode=”Always” with your page directives, which will encrypt the view state data. You can add this in following way
Page Language=”C#” EnableViewState=”true” ViewStateEncryptionMode=”Always”
Session State
A cookie is very simple and is not suitable for sophisticated storage requirements. Session state is a workaround for this problem and it gives a method to keep more complex objects securely. ASP.NET allows programmers to keep any type of objects in session. Data stored in session will be kept in server memory and it is protected as it will never get transmitted to a client. Every client that uses the application will have separate sessions. Session state is ideal for storing user specific information.
The following code shows storing a string value in session.
Session["name"] = “Manu”;
Session accepts a System.Object type. So you need a type cast when reading. Reading values from session is like
string name = Session["name"] as string;
// null checking is needed as session may not exist
The following shows different methods used.
* Session.Abandon() – Cancels the session and fires end event. This is used when you are done with the session.
* Session.Clear() / Session.RemoveAll() – Clears all contents of the session. This will not end the session.
* Session.Remove(string) – Removes the session name supplied.
How Session Works?
ASP.NET maintains a unique id which is called as “session id” for each session. This id is generated using a custom algorithm and it is unique always. Session id will be sent to the client as a cookie and the browser resends this upon each request. ASP.NET uses this session id to identify the session object.
Session Timeout
Each session will have a timeout value (default 20Mins). If the page is not getting any requests within the timeout limit specified, ASP.NET will assume that the user has left the application and it immediately terminates the session and fires the End event. This helps the server to cleanup unused sessions and gives room for new requests. Timeout value can be changed from web.config file or through code. Timeout value is specified in minutes.
or
Session.Timeout = 60;
Where Session is Stored?
ASP.NET allows three types of session storages.
* InProc – – This is the default session storage. Session data will be kept in the server memory.
* StateServer – – It runs as a separate windows service and keeps the session data out of ASP.NET process memory area. To access session, ASP.NET process has to communicate with this external process.
* SQL Server – – It allows to keep session data in SQL Server.
Note: //Bad code ! don’t use
string name = Session["name"].ToString();
Another problem with session is that it is not strongly typed. Session keeps System.Object type which means every .NET type can be kept in session. Consider the following code
Session["age"] = “I can store a value that is not number!”;
Since it is not strongly typed, Session["age"] can contain any value and you will have problems when using this. Also, you may make typing mistakes when typing the session names. This will also lead to unexpected behaviors. The following section describes workarounds for these problems.
Wrapping Session in a Strongly Typed Class
To workaround the above problems, we can create a strongly typed wrapper classes around the session and route all calls to session through this wrapper. Consider a simple scenario where you need to keep user details like name, age, email validated etc in a session. We create a class to represent all required fields. See the following code
{
// This key is used to identify object from session
const string KEY = “personDetails”;
public PersonSession(int id,string name,int age,bool emailValidated)
{
this.Id = id;
this.Name = name;
this.Age = age;
this.HasEmailValidated = emailValidated;
}
public static PersonSession GetPersonSession() {
return HttpContext.Current.Session[KEY] as PersonSession;
}
public static void CreatePersonSession(PersonSession person) {
HttpContext.Current.Session[KEY] = person;
}
public int Id { get; private set; }
public string Name { get; private set; }
public int Age { get; private set; }
public bool HasEmailValidated { get; private set; }
}
The above given class abstracts the session access and provides a clear interface to access the session contents safely. The static methods CreatePersonSession and GetPersonSession can be used to create and get details of a person from session. The following code shows how to store person details into session.
PersonSession person = new PersonSession(int.Parse(txtPersonId.Text),
txtName.Text, int.Parse(txtAge.Text), chkEmailValidated.Checked);
PersonSession.CreatePersonSession(person);
To retrieve person details, you need to do
PersonSession person = PersonSession.GetPersonSession();
// if session not exist, this will return NULL
if (person != null) {
// person exist. Use person’s properties to get values
}

[...] State Management in ASP.NET – View State and Session State November 2009 [...]