You often hear how the Web is meant to be stateless. What it actually means is HTTP (the protocol over which Internet or the Web works) is a stateless protocol and it works on Requests from Clients to Server and Responses from Server back to Clients. Beyond a Request/Response cycle, the server doesn’t know/care about the state of the client.
ASP.NET WebForms is an abstraction that was built on top of HTTP, but it was primarily designed as an easy path for Developers from the Visual Basic world to migrate to the web world. So it mimicked things like Controls, events, event handlers and even State. ASP.NET provides a number of ways to preserve the state/data between round trips. In this article, we will briefly explore some of these ways.
Data can be maintained between round trips at two different locations. Yes you guessed it right – on the Client Side or the Server Side. Take a look at the following diagram which shows different options for maintaining the state on client as well as the server-
Taking an informed decision of storing what kind of data where, is a crucial part of each web application design. Usually non-secure information is stored at client side and secured information is always stored at the server side.
Client Side State Management
Client-side management techniques don’t utilize server resources. They are less secure but fast performing. Let’s explore some client-side techniques to save state:
ViewState - ViewState is ASP.NET’s own integrated state serialization mechanism. ViewState objects are used to store page related data which are preserved between the round trips from client to server and server to client. View state is maintained as a hidden field in the page. Here’s how viewstate for an ASP.NET textbox would look like if you view the page source:
Let’s see ViewState in action with an example. Design a simple web form and add a button on the web form. Write the following code in the code behind of the web form -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["PageHitCounter"] = 0;
}
}
protected void btnPageHitCounter_Click(object sender, EventArgs e)
{
ViewState["PageHitCounter"] = Convert.ToInt32(ViewState["PageHitCounter"]) + 1;
Response.Write("The number of postbacks are - " + ViewState["PageHitCounter"].ToString());
}
This code shows how many times the page has been posted back to the server. Now normally with every rountrip the PageHitCounter would be reset to 0, but since we are using ViewState, the counter gets preserved between round trips.
Query String - Query String is passed in the URL. They store the value in the form of Key-Value pair. You will have to maintain the Query Strings when you pass it from one page to second page and second page to the third page.
For example, when redirecting a request from one page to another page, you can pass the Query String as shown here -
Response.Redirect("menu.aspx?category=vegfood");
Query string is limited to simple string information, and they’re easily accessible and readable.
Hidden Fields - Hidden Fields are similar to a text box but does not get displayed on the UI. However you can see the value of hidden fields when you view page source in the browser. Using Hidden Fields, you can pass information from one page to another page without the end user's knowledge, primarily for internal processing.
Drag and Drop a hiddenfield control on the web page from the Visual Studio toolbox and set its value in the Page Load event as shown below -
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
siteReference.Value = "https://www.dotnetcurry.com";
}
}
Run the page and check the source code. You will see the Hidden Field value as shown below -
Cookies - Cookies are small files that are created in the web browser’s memory or on the client’s hard disk. The maximum size of a cookie file is 4 KB. You can create two types of cookies. Transient Cookie (memory) and Persistent Cookie (hard disk). Transient Cookies are accessible till the time the browser is running. Persistent Cookies are cookies which have an expiry time. When you don't set expiry time for the cookie, the cookies are treated as transient cookies.
Cookie contains a Key/Value pair. Cookie can also contain the collection of key/value pairs. Let's see an example of a Cookie -
Response.Cookies["CityName"].Value = "London";
HttpCookie dncCookie = new HttpCookie("DotNetCurry");
dncCookie.Values["ArticleName"] = "SharePoint 2013 - Business Connectivity Services";
dncCookie.Values["Author"] = "SharePoint Admin";
dncCookie.Values["PublishDate"] = DateTime.Now.AddDays(10).ToLongDateString();
dncCookie.Values["ArticleName"] = "SharePoint 2013 - Business Connectivity Services";
dncCookie.Expires = DateTime.Now.AddDays(20);
Response.AppendCookie(dncCookie);
Just like query strings, cookies are limited to storing simple strings. Users also disable cookies or manually delete them which renders them ineffective.
Server Side State Management
Unlike Client-side state management techniques, Server-side options are more secure but can become slow to respond, depending on the information that is stored. Since these techniques directly use the resources of the web server, scalability issues is something to be considered when storing large amount of data.
ASP.NET provides some options to implement server-side state management:
Application State - The Application object is an instance of the System.Web.HttpApplicationState class. You can create Application Level object like a name/value pair and share it across all users. You can declare Application level variable when the web application starts. Usually developers declare Application Level variables in Global.asax file. The Global.asax file contains events (Application_Start Event, Application_End Event and Application_Error Event) which get associated with Application object.
You can declare Application level objects in the Application_Start event. Let's see an example -
Add a Global.asax file in your web application and write the following code in the Application_Start event -
void Application_Start(object sender, EventArgs e)
{
Application["CopyRightNote"] = "DotNetCurry CopyRight 2013-2014";
Application["HitCounter"] = 0;
}
void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["HitCounter"] =Convert.ToInt32(Application["HitCounter"]) + 1;
Application.Lock();
}
Now you can access both application variables on any page.
Session State – Session objects are stored on the server side and are an instance of the System.Web.SessionState.HttpSessionState class. It can be used to store any type of data in the memory. They are primarily used for storing user specific information like shopping cart, preferences etc and is never transferred to the client. You can declare session level variables in the following manner -
Session["AccountNo"] = 1998773887324556;
By default sessions are stored in server memory called as In-Process. You can also store session as out-of-process. You can store the session information in Microsoft SQL Server or State Server. Session state must be used thoughtfully as it leads to scalability issues if misused.
Cache - The Cache object is an instance of the System.Web.Caching.Cache class. Cache is stored on the server side and is more scalable in nature, as ASP.NET removes objects if the memory becomes scarce. This also makes it unreliable in some cases. Cache objects can have expiration polices set on them and is shared across users. You can implement Page Caching and Data Caching. Let's see a small example of both.
Page Caching -
Data Caching -
Cache.Insert("CacheDateTime", DateTime.Now);
You can also cache client-side by using the Location=”Client” option.
Profile - Profile data is stored in the SQL Server database by default. This database structure is preset, so if you want any custom user details to be stored, you will need to create a custom database and write a custom provider for it. Profiles are designed to store information permanently. Here’s a simple example of using profiles:
Using the profile properties in your application -
Profile.FirstName = "John";
Profile.LastName = "Mark";
Profile.City = "London";
Profile.Age = 46;
The Profile object provides you with a persistent form of session state that is strongly typed.
Context.Items - The HttpContext object is provided by the Page.Context property. The HttpContext.Items collection can be used to temporarily store data across postback. View state and session state can be used for a similar effect, but they assume longer-term storage. Context can be used for storing data for one request only. We can store it as a key/value pair as shown below -
Context.Items["SocialPinNo"] = 3666736;
Response.Write(Context.Items["SocialPinNo"].ToString());
Conclusion
That was a brief introduction to some state management techniques in ASP.NET. We have seen that there is a hidden overhead to maintain and transfer client state to the server every time an action is performed on client and handled on the server. We have also seen if state management techniques are not used with care, they can clog up server resource causing scalability issues. Make sure you take an informed decision while deciding which state management technique you opt for.
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Pravinkumar, works as a freelance trainer and consultant on Microsoft Technologies. He is having over 10 years of experience in IT and is also a Microsoft Certified Trainer(MCT). He has conducted various corporate trainings on all versions of .NET Technologies including .NET, SharePoint Server, Microsoft SQL Server, Silverlight, ASP.NET, Microsoft PerformancePoint Server 2007 (Monitoring). He is passionate about learning new technologies from Microsoft. You can contact Pravinkumar at dabade[dot]pravinkumar [attherate] gmail[dot]com