ASP.NET  

State Management in ASP.NET: ViewState, Session, Cookies & Cache

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

  • Remember control values after button click

    1. Forms

    2.Dropdowns, Textboxes

Limitations

  • Increase page size (slower page load)

  • Works only in Web Forms (not MVC/Core)

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

  • Shopping cart

  • User login info

  • Banking portal session security

Limitations

  • Uses server memory

  • Too many sessions affect performance

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

  • Remember Me login

  • Store user preferences (language, theme)

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

  • Max 4KB size

  • Stored on client → less secure

4. Cache

What It Is

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

Use Case

  • Load product catalog once, reuse many times

  • Caching stock market data

  • Caching configuration and lookup tables

Example

Insert into Cache

Cache["StockPrice"] = 102.55;

Retrieve

var price = Cache["StockPrice"];

Remove

Cache.Remove("StockPrice");

Benefit

  • Improves performance

  • Reduces database calls

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