State Management Techniques in ASP.NET
This article discusses various options for state management for web applications developed using ASP.NET. Generally, web applications are based on stateless HTTP protocol which does not retain any information about user requests. In typical client and server communication using HTTP protocol, page is created each time the page is requested.
Developer is forced to implement various state management techniques when developing applications which provide customized content and which "remembers" the user.
Here we are here with various options for ASP.NET developer to implement state management techniques in their applications. Broadly, we can classify state management techniques as client side state management or server side state management. Each technique has its own pros and cons. Let's start with exploring client side state management options.
Client side State management Options:
ASP.NET provides various client side state management options like Cookies, QueryStrings (URL), Hidden fields, View State and Control state (ASP.NET 2.0). Let's discuss each of client side state management options.
Bandwidth should be considered while implementing client side state management options because they involve in each roundtrip to server. Example: Cookies are exchanged between client and server for each page request.
Cookie: Response.Cookies["UserId"].Value=username;
A cookie is a small piece of text stored on user's computer. Usually, information is stored as name-value pairs. Cookies are used by websites to keep track of visitors. Every time a user visits a website, cookies are retrieved from user machine and help identify the user.
Let's see an example which makes use of cookies to customize web page.
if (Request.Cookies["UserId"] != null)
lbMessage.text = "Dear" + Request.Cookies["UserId"].Value + ", Welcome to our website!";
else
lbMessage.text = "Guest,welcome to our website!";
Advantages:
Disadvantages:
Hidden fields: protected System.Web.UI.HtmlControls.HtmlInputHidden Hidden1; //to assign a value to Hidden field Hidden1.Value="Create hidden fields"; //to retrieve a value string str=Hidden1.Value; Disadvantages:
View State: // Add item to ViewState ViewState["myviewstate"] = myValue; //Reading items from ViewState Disadvantages:
Query strings:
Query strings are usually used to send information from one page to another page. They are passed along with URL in clear text. Now that cross page posting feature is back in asp.net 2.0, Query strings seem to be redundant. Most browsers impose a limit of 255 characters on URL length. We can only pass smaller amounts of data using query strings. Since Query strings are sent in clear text, we can also encrypt query values. Also, keep in mind that characters that are not valid in a URL must be encoded using Server.UrlEncode.
Let's assume that we have a Data Grid with a list of products, and a hyperlink in the grid that goes to a product detail page, it would be an ideal use of the Query String to include the product ID in the Query String of the link to the product details page (for example, productdetails.aspx?productid=4).
When product details page is being requested, the product information can be obtained by using the following codes:
string productid; Advantages:
Disadvantages:
Control State:
Control State is new mechanism in ASP.NET 2.0 which addresses some of the shortcomings of View State. Control state can be used to store critical, private information across post backs. Control state is another type of state container reserved for controls to maintain their core behavioral functionality whereas View State only contains state to maintain control's contents (UI). Control State shares same memory data structures with View State. Control State can be propagated even though the View State for the control is disabled. For example, new control Grid View in ASP.NET 2.0 makes effective use of control state to maintain the state needed for its core behavior across post backs. Grid View is in no way affected when we disable View State for the Grid View or entire page
Server Side State management:
As name implies, state information will be maintained on the server. Application, Session, Cache and Database are different mechanisms for storing state on the server.
Care must be taken to conserve server resources. For a high traffic web site with large number of concurrent users, usage Application object:
Application object is used to store data which is visible across entire application and shared across multiple user sessions. Data which needs to be persisted for entire life of application should be stored in application object.
In classic ASP, application object is used to store connection strings. It's a great place to store data which changes infrequently. We should write to application variable only in application_Onstart event (global.asax) or application.lock event to avoid data conflicts. Below code sample gives idea
Application.Lock(); Application["mydata"]="mydata"; Application.UnLock(); Session object is used to store state specific information per client basis. It is specific to particular user. Session data persists for the duration of user session you can store session's data on web server in different ways. Session state can be configured using the <session State> section in the application's web.config file.
Configuration information: Mode: This setting takes a Boolean value of either true or false to indicate whether the Session is a cookie less one.
Timeout:
This indicates the Session timeout vale in minutes. This is the duration for which a user's session is active. Note that the session timeout is a sliding value; Default session timeout value is 20 minutes This identifies the database connection string that names the database used for mode SQLServer. In the out-of-process mode State Server, it names the server that is running the required Windows NT service: aspnet_state. You can disable session for a page using EnableSessionState attribute. You can set off session for entire application by setting mode=off in web.config file to reduce overhead for the entire application.
Session state in ASP.NET can be configured in different ways based on various parameters including scalability, maintainability and availability
In process mode: Configuration information:
<sessionState mode="Inproc" sqlConnectionString="data source=server;user id=freelance;password=freelance" cookieless="false" timeout="20" /> Disadvantages:
Out-of-process Session mode (state server mode): Net start aspnet_state
Configuration information: Disadvantages:
SQL-Backed Session state:
ASP.NET sessions can also be stored in a SQL Server database. Storing sessions in SQL Server offers resilience that can serve sessions to a large web farm that persists across IIS restarts. Configuration Information:
<sessionState mode="SQLServer" sqlConnectionString="data source=server;user id=freelance;password=freelance" cookieless="false" timeout="20" /> Disadvantages:
Choosing between client side and Server side management techniques is driven by various factors including available server resources, scalability and performance. We have to leverage both client side and server side state management options to build scalable applications.
When leveraging client side state options, ensure that little amount of insignificant information is exchanged between page requests.
Various parameters should be evaluated when leveraging server side state options including size of application, reliability and robustness. Smaller the application, In process is the better choice. We should account in the overheads involved in serializing and deserializing objects when using State Server and Database based session state. Application state should be used religiously.
Hidden fields are used to store data at the page level. As its name says, these fields are not rendered by the browser. It's just like a standard control for which you can set its properties. Whenever a page is submitted to server, hidden fields values are also posted to server along with other controls on the page. Now that all the asp.net web controls have built in state management in the form of view state and new feature in asp.net 2.0 control state, hidden fields functionality seems to be redundant. We can still use it to store insignificant data. We can use hidden fields in ASP.NET pages using following syntax
View State can be used to store state information for a single user. View State is a built in feature in web controls to persist data between page post backs. You can set View State on/off for each control using EnableViewState property. By default, EnableViewState property will be set to true. View state mechanism poses performance overhead. View state information of all the controls on the page will be submitted to server on each post back. To reduce performance penalty, disable View State for all the controls for which you don't need state. (Data grid usually doesn't need to maintain state). You can also disable View State for the entire page by adding EnableViewState=false to @page directive. View state data is encoded as binary Base64 - encoded which add approximately 30% overhead. Care must be taken to ensure view state for a page is smaller in size. View State can be used using following syntax in an ASP.NET web page.
Response.Write(ViewState["myviewstate"]);
productid=Request.Params["productid"];
of sessions object for state management can create load on server causing performance degradation
<sessionState mode = <"inproc" | "sqlserver" | "stateserver">
cookieless = <"true" | "false">
timeout = <positive integer indicating the session timeout in minutes>
sqlconnectionstring = <SQL connection string that is only used in the SQLServer mode>
server = <The server name that is only required when the mode is State Server>
port = <The port number that is only required when the mode is State Server>
This setting supports three options. They are InProc, SQLServer, and State Server
Cookie less:
SqlConnectionString:
Server:
Port:
This identifies the port number that corresponds to the server setting for mode State Server. Note that a port is an unsigned integer that uniquely identifies a process running over a network.
This mode is useful for small applications which can be hosted on a single server. This model is most common and default method to store session specific information. Session data is stored in memory of local web server
This mode is ideal for scalable and highly available applications. Session state is held in a process called aspnet_state.exe that runs as a windows service which listens on TCP port 42424 by default. You can invoke state service using services MMC snap-in or by running following net command from command line.
<sessionState mode="StateServer"
StateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=freelance; password=freelance"
cookieless="false" timeout="20"/>
SQL based Session state is configured with aspnet_regsql.exe. This utility is located in .NET Framework's installed directory
C:\<windows>\microsoft.net\framework\<version>. Running this utility will create a database which will manage the session state.

Sandeep SiddhaparaPosted Aug 6, 2020, 5:22 AM
Such a nice and easily understandable about state management technique.
Bhavesh JadavPosted Aug 18, 2018, 2:00 AM
Super explanation sir, thanks to share it.
Chandan KumarPosted Jun 24, 2018, 1:51 AM
It's really a very helpful article I have found on the internet Thank a lot Sir...
Sakshi GuptaPosted Jun 15, 2016, 2:05 AM
what is the meaning of using viewstate at application level, is this mean we can use viewstate between different pages??? plzz explain...
Munesh SharmaPosted May 22, 2016, 12:23 PM
Good one
Yatendra SharmaPosted Mar 15, 2016, 6:20 AM
great article thanks for sharing:)
anil maskePosted Sep 18, 2015, 8:34 AM
It's really very nice article.........
FAROOKH MANSURIPosted Sep 4, 2015, 2:21 AM
It's really nice article.........
Venkatesh ChitlaPosted Jan 20, 2015, 2:07 AM
is there any video explanation about this topic
Shivanand ArurPosted Jan 19, 2015, 3:19 AM
Thank you everyone :)
Manish Kumar ChoudharyPosted Jan 18, 2015, 6:10 AM
Nice one..
vinayak ghantiPosted Jan 18, 2015, 2:41 AM
Shiva only one word Super...
Nilesh AmrutkarPosted Jan 16, 2015, 12:45 PM
lai bhari
sukumar sPosted Jan 9, 2015, 5:25 AM
Nice article ...
kiran kadamPosted Dec 22, 2014, 9:13 AM
nice....
Mahesh MahaaPosted Sep 10, 2014, 7:33 AM
Really awesome .....excellent article on State management
Muneeb Hasham.KPosted May 21, 2014, 7:43 PM
before reading your article state management was difficult for me to understand but now i have understood it very well :) thanks for such nice explanation.
Sandeep SharmaPosted May 14, 2014, 8:56 AM
Great Job done on ASP.NET State Management and Behaviour. This Article is with complete knowledge on it and appreciated Shivanand Arur Sir. Greets you!! (Keep it up for more.)
Rahul WaghmodePosted Jan 10, 2014, 12:42 AM
good one ddd
Ashish GuptaPosted Dec 25, 2013, 6:14 AM
great article.
Manish swamiPosted Nov 22, 2013, 2:30 AM
Great work...!!!
Shivanand ArurPosted Apr 16, 2013, 7:05 AM
Thanks Ravi.
Ravi ShekharPosted Apr 13, 2013, 12:53 PM
Realy nice....in simplest way!!
Shivanand ArurPosted Jan 21, 2013, 8:31 AM
Thank u Dhanoop... :)
Dhanoop APosted Jan 21, 2013, 7:52 AM
Good Article
Shivanand ArurPosted Nov 27, 2012, 7:58 AM
Thank u Chaitanya... M Glad u liked it... :)
Chaitanya JayanthiPosted Nov 27, 2012, 5:20 AM
simple and easy to understand article..
Shivanand ArurPosted Sep 25, 2012, 2:55 PM
Thank you Sukesh... :)
Sukesh MarlaPosted Sep 25, 2012, 2:52 PM
Good start buddy, keep on...
Shivanand ArurPosted Sep 22, 2012, 12:53 AM
Thank you Viet...
viet vo quocPosted Sep 21, 2012, 8:31 PM
Very great! Thanks so much.
Shivanand ArurPosted Sep 17, 2012, 10:26 AM
Thank you Dinesh
Dinesh BeniwalPosted Sep 17, 2012, 9:26 AM
Good Start Shivanand.
Shivanand ArurPosted Sep 17, 2012, 8:20 AM
Thank you, Ashwini for your valuable feedback...
ashwini sawantPosted Sep 17, 2012, 8:18 AM
Nice Article. You have missed Control state. This is also one of the Client Side State management technique. If you create a custom control that requires view state to work properly, you should use control state to ensure other developers don’t break your control by disabling view state. you can get deep knowledge here http://www.c-sharpcorner.com/UploadFile/scottlysle/ASPControlState01292007010407AM/ASPControlState.aspx Regards Ashwini S Sawant
Shivanand ArurPosted Sep 17, 2012, 8:11 AM
Thank you, Rahul. I have not mentioned about the Global.asax file but the events for the Application Object are mentioned above.... It's just that I have not specifically mentioned "Global.asax" file name above...
Rahul WaghmodePosted Sep 17, 2012, 6:42 AM
Hi Anand , it's very good article but u can't explain the details of Sesion & Global.asax where u can maintain the application & session events.
Shivanand ArureditedPosted Sep 17, 2012, 1:13 AMEdited Sep 17, 2012, 2:34 AM
Thank you very much Rohatash and Deepak. @Deepak - Sorry, forgot to add about Caching...
Deepak MiddhaPosted Sep 17, 2012, 12:28 AM
Hi Shivanand,your article is very good and provide a deep knowledge about state management, but you not explain cache which is also a server side object and use to manage the state.
Rohatash KumarPosted Sep 17, 2012, 12:08 AM
very good demonstration. Thanks