Roadmap › ASP.NET Web Forms — Page Life Cycle, ViewState, Controls and State Management › Module: PostBack and State
Lessons in this course (10)
3. PostBack, AutoPostBack and ViewState — how they work
Intermediate★ Must knowLesson 3 of 10
- A Web Forms page wraps everything in one
<form runat="server">that posts back to the same URL. - PostBack = the browser submits the form to the same page; the page object is created again from scratch on the server, rebuilds controls, restores state and raises the events.
AutoPostBack="true"makes controls like DropDownList post immediately on change (via__doPostBackJavaScript);__EVENTTARGETand__EVENTARGUMENThidden fields tell the server which control fired.IsPostBackisfalseon the first GET andtrueon postbacks.
ViewState:
html
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKLTY1NDU2MTc0MQ9kFgJmD2QWAg..." />- Stores control properties that changed programmatically (e.g. a Label's text, a GridView's data) so they survive postbacks.
- Base64-encoded, signed (MAC) to prevent tampering, optionally encrypted (
ViewStateEncryptionMode) — but not secret by default; never store sensitive data. - Grows page size and slows requests — large GridViews can produce hundreds of KB.
- Control:
EnableViewState="false"per control/page,ViewStateMode="Disabled"+ enable selectively (4.0+), store state elsewhere. - ControlState — a small, separate state that controls need to function (e.g. GridView page index); cannot be turned off.
csharp
// Your own values in ViewState (per page, survives postbacks of that page)
private int CurrentStep
{
get => (int?)ViewState["Step"] ?? 1;
set => ViewState["Step"] = value;
}