Introduction

In web applications, HTTP is stateless, meaning it does not store information between requests.
To remember user actions, login details, shopping cart data, etc., ASP.NET uses state management techniques.

There are two types:

TypeExample
Client-Side State ManagementViewState, Cookies, Hidden Fields, QueryString
Server-Side State ManagementSession, Cache, Application State

In this article, we will explain ViewState, Session, Cookies, Cache with real-time examples and code.


1. ViewState

What It Is

ViewState stores values in the page (client side) and retains them during postbacks.

Use Case

Limitations

Example

ASPX Page

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:Button ID="btnSave" runat="server" Text="Save" OnClick="btnSave_Click"/>
<asp:Label ID="lblResult" runat="server"/>

Code Behind

protected void btnSave_Click(object sender, EventArgs e)
{
    ViewState["UserName"] = txtName.Text;
    lblResult.Text = "Saved: " + ViewState["UserName"];
}

2. Session

What It Is

Session stores data per user on the server until the browser is closed or timeout (default 20 min).

Real-Time Use Case

Limitations

Example

Store in Session

Session["UserId"] = 101;

Retrieve

int userId = Convert.ToInt32(Session["UserId"]);

Remove

Session.Remove("UserId");

3. Cookies

What It Is

Cookies store data in the browser.

Use Case

Example

Create Cookie

HttpCookie ck = new HttpCookie("UserName");
ck.Value = "Sandhiya";
ck.Expires = DateTime.Now.AddDays(7);
Response.Cookies.Add(ck);

Read Cookie

string name = Request.Cookies["UserName"].Value;

Delete Cookie

Response.Cookies["UserName"].Expires = DateTime.Now.AddDays(-1);

Limitations

4. Cache

What It Is

Cache stores frequently used data on the server for fast access.

Use Case

Example

Insert into Cache

Cache["StockPrice"] = 102.55;

Retrieve

var price = Cache["StockPrice"];

Remove

Cache.Remove("StockPrice");

Benefit

Comparison Table

FeatureViewStateSessionCookiesCache
StoragePage (Client)ServerBrowserServer
LifetimePage until postbackBrowser session / TimeoutDepends on expiryUntil memory clears
SizeMediumLargeSmall (4KB)Large
UseForm controlsUser infoPreferencesPerformance
SecurityMediumHighLowMedium

Real-Life Scenario Example

ScenarioBest Option
Keep text after button clickViewState
Keep logged-in user detailsSession
Remember the user for 7 daysCookies
Cache product list for fast loadCache

Conclusion

State management helps web applications remember user actions and improve performance. Choosing the right method depends on security, memory, and the duration needed.

Best ForTechnique
Temporary page dataViewState
User login infoSession
Remember meCookies
Speed & performanceCach