Roadmap › ASP.NET Web Forms — Page Life Cycle, ViewState, Controls and State Management › Module: PostBack and State
Lessons in this course (10)
4. State management — client-side vs server-side
Intermediate★ Must knowLesson 4 of 10
| Technique | Where stored | Scope / lifetime | Use for |
|---|---|---|---|
| ViewState | Hidden field in the page | One page, across its postbacks | Control values, small page data |
| ControlState | Hidden field | One control | Essential control data |
| Hidden field | Page | Postbacks | Small values for client script |
| Query string | URL | One request/link | Ids, filters, bookmarkable state (?id=5) — visible, validate it |
| Cookies | Browser | Until expiry | Preferences, "remember me" (4 KB limit) |
| Session | Server (InProc memory, StateServer, SQL Server) keyed by a cookie | One user, until timeout (20 min default) | Cart, user data during a visit |
| Application | Server memory | Whole app, all users, until restart | Rarely-changing global data (with locking) |
Cache (HttpRuntime.Cache) | Server memory | All users, with expiry/dependencies | Expensive lookups, reference data |
| Profile | Database (provider) | Per user, permanent | User preferences (legacy) |
csharp
Session["Cart"] = cart; // InProc by default
var cart = Session["Cart"] as Cart ?? new Cart();
Application.Lock(); Application["Visitors"] = (int)(Application["Visitors"] ?? 0) + 1; Application.UnLock();
Cache.Insert("Categories", categories, null, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration);
Response.Cookies.Add(new HttpCookie("theme", "dark") { Expires = DateTime.Now.AddDays(30), HttpOnly = true, Secure = true });
Response.Redirect("Orders.aspx?customerId=" + customerId, endResponse: false);Session modes (web.config <sessionState mode="...">): InProc (fastest; lost on app-pool recycle; not shared in a web farm), StateServer (separate Windows service; survives recycles), SQLServer (durable, shared across a farm), Custom (Redis provider), Off. Objects stored out-of-process must be [Serializable].
Page navigation: Response.Redirect (browser makes a new request — URL changes, 302), Server.Transfer (server switches page — URL doesn't change, same request), cross-page posting (PostBackUrl).