ASP.NET Web Forms — Page Life Cycle, ViewState, Controls and State Management
In short: Page request → start (IsPostBack set) → PreInit (set master/theme, create dynamic controls) → Init (controls initialised) → InitComplete → load ViewState and postback data (postbacks) → PreLoad → Load (page then controls;
- load data in
!IsPostBack) → control events (change events, then the Click that caused the postback) → LoadComplete → PreRender (final changes) → SaveStateComplete (ViewState saved) → Render (HTML written) → Unload (cleanup). - Mnemonic SILVER: Start, Init, Load, Validate, Event, Render.
In short: A hidden form field (__VIEWSTATE) holding base64-encoded, MAC-signed state of controls (and your own values) so they survive postbacks of the same page without server memory.
- Pros: automatic, per-page, no server storage.
- Cons: increases page size and request time, not secure by default (only signed, not encrypted), can't be used across pages.
- Disable it where unnecessary and never store sensitive data.
In short: A postback is the form submitting back to the same page so server-side events (button clicks, selection changes) can run.
IsPostBackis false on the first request and true on postbacks — load initial data only when!IsPostBack, otherwise you overwrite the user's input and waste database calls.
In short: Client-side: ViewState, ControlState, hidden fields, cookies, query strings.
- Server-side: Session (InProc, StateServer, SQLServer, custom), Application, Cache, Profile.
- Choose by scope (page, user, all users), size, security and whether it must survive restarts or work in a web farm.
In short: Response.Redirect sends a 302 to the browser, which makes a new request — URL changes, works for any URL, an extra round trip, previous page data lost unless passed.
Server.Transferswitches execution to another page on the server within the same request — URL in the browser stays the same, faster, can access the previous page (PreviousPage), only within the same application.
In short: InProc (in the worker process memory — fastest, lost on app-pool recycle, not shared), StateServer (aspnet_state service — survives recycles, shared, serialisation needed), SQLServer (stored in SQL — durable, shared, slower), Custom (e.g. Redis provider), Off.
- In a web farm use SQLServer, StateServer or a Redis custom provider (or sticky sessions as a weaker alternative).
In short: A user control (.ascx) is markup + code-behind built visually and reused within one application (registered with @Register Src=).
- A custom (server) control is a class deriving from
Control/WebControl/CompositeControlthat renders its own HTML, compiled into a DLL, reusable across applications, can appear in the Toolbox and support design-time features — more work to build.
In short: A master page (.master) defines a shared layout with ContentPlaceHolders; content pages specify MasterPageFile and fill placeholders with <asp:Content>.
- At runtime the master page is merged into the page's control tree (as a child control).
- Access it with
Master(strongly typed via@MasterType), switch it dynamically inPreInit, nest masters for sections.
In short: Global.asax holds application-level event handlers: Application_Start/End, Session_Start/End, BeginRequest, AuthenticateRequest, Application_Error.
- Web.config holds hierarchical configuration: connection strings, app settings, authentication/authorization, session, custom errors, modules/handlers, compilation;
- changes restart the app.
In short: Modules (IHttpModule) subscribe to pipeline events and run for every request — authentication, logging, URL rewriting, compression.
- Handlers (
IHttpHandler) generate the response for specific requests/extensions — the Page handler for.aspx,.ashxgeneric handlers for images or files. - A request passes through many modules but is processed by one handler.
In short: It turns a full postback into an asynchronous partial postback: the browser still posts the whole form including ViewState, the server runs the full page life cycle, but only the panel's markup (and updated ViewState) is returned and replaced.
- It improves perceived responsiveness, not server load.
- For light calls use page methods or Web API with JavaScript.
In short: Try/catch for expected errors in handlers;
Page_Errorfor page-level handling;Application_Errorin Global.asax to log every unhandled exception (Server.GetLastError()), thencustomErrors/httpErrorsin web.config to show friendly error pages (404, 500) instead of details.- Use a logging framework or ELMAH.
In short: Because controls created in code must be recreated on every request, with the same IDs, early enough (PreInit/Init) for ViewState and posted data to be applied and events to fire.
- Creating them in Load or only on the first request (
!IsPostBack) means the control doesn't exist when the framework restores state and raises events.
In short: Web Site: no project file, files compiled dynamically on the server (each page/folder its own assembly), App_Code for shared classes, easy to edit live but harder to manage.
- Web Application:
.csproj, compiled ahead into one assembly inbin, designer files, better for builds, refactoring, source control and deployment — the standard for professional projects.
In short: Measure page size: ViewState of the GridView is likely hundreds of KB.
- Disable ViewState on the grid and rebind on postback, or keep only keys;
- use server-side paging (load only the current page from the database) instead of binding thousands of rows;
- replace UpdatePanels around the grid with lighter AJAX calls if needed;
- cache reference data;
- check SQL queries and session locking.
In short: Put the business logic in a separate class library (netstandard2.0 or .NET Framework library with clean interfaces) and unit-test it;
- keep code-behind thin, calling services.
- If the feature is a new area, consider building it directly in the new ASP.NET Core app behind a reverse proxy sharing authentication (strangler pattern), so it doesn't need to be migrated later.
In short: InProc session lost when the app pool recycles (scheduled recycling, memory limits, web.config/bin changes, crashes) or when requests hit different servers in a web farm without shared session;
- session timeout too short;
- cookieless/cookie issues.
- Fix: StateServer/SQLServer/Redis session, review recycling settings, store less in session, sticky sessions only as a stop-gap.