Tuesday, November 11, 2014

Difference Between View State and Session State in ASP.Net

Both view state and session state are used to store and read data in asp.net application. The following table shows the difference between view state and session state.


View State
Session State
It is maintained in page level only.
It is maintained across session level
The information in View State of one page is not visible in another page. If you want to access information in same page, then you can use view state.
Its value is available in all pages within a user session. If you want to access the information on different web pages, you can use session state.
It stores data between post backs by putting it into one or more hidden form fields on the client page as base64-encoded strings. That's why It is also knows as a client side state management technique. Because the data in view state is stored as a string, only objects that can be serialized can be stored inside view state.
It's information stored in server. That's why it is also known as server side state management technique.
The information in the hidden view state field can be seen if the page output source is viewed, creating a potential security issue. To mitigate this issue, you can encrypt view state by setting the viewStateEncryptionMode attribute in the @ Page directive to "Always
 It is more secure than View State as the data value is stored in server side. It can be stored on Inproc, OutProc, SqlServer.
When the page is Posted Back, the values are read from the hidden form field and stored in memory until the page has finished processing. If view state is particularly large (KBs not 10 bytes), it can negatively affect the speed at which the HTML doc is downloaded by the browser.
It persist the data of particular user in the server. This data available till user close the browser or session time completes.
It is used to persist form fields and custom data on client side.
It used to persist the user-specific data on the server side.
Any value can be stored in view state by using syntax
ViewState.Add("identifier-name", value);
For example,
String firstName =”John”;
ViewState.Add("FirstName", firstName);
Any value can be stored in session state by using syntax Session[“identifier-name”] =value;
For example,
String firstName =”John”;
Session[“FirstName”] =firstName;
A value can be read from view state by using syntax
ViewState["identifier-name"].
For example,
String firstName  = (String)ViewState["FirstName"];
A value can be read from session state by using syntax Session[“identifier-name”].
For example,
String firstName  = (String)Session[“FirstName”];