Lessons in this course (10)

4. State management — client-side vs server-side

Intermediate★ Must knowLesson 4 of 10
TechniqueWhere storedScope / lifetimeUse for
ViewStateHidden field in the pageOne page, across its postbacksControl values, small page data
ControlStateHidden fieldOne controlEssential control data
Hidden fieldPagePostbacksSmall values for client script
Query stringURLOne request/linkIds, filters, bookmarkable state (?id=5) — visible, validate it
CookiesBrowserUntil expiryPreferences, "remember me" (4 KB limit)
SessionServer (InProc memory, StateServer, SQL Server) keyed by a cookieOne user, until timeout (20 min default)Cart, user data during a visit
ApplicationServer memoryWhole app, all users, until restartRarely-changing global data (with locking)
Cache (HttpRuntime.Cache)Server memoryAll users, with expiry/dependenciesExpensive lookups, reference data
ProfileDatabase (provider)Per user, permanentUser 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).