Session state vs ViewState in ASP.NET
Web Forms offers two convenient places to keep values between requests. ViewState travels with the page, inside a hidden form field, and lives only as long as the user keeps posting back that page. Session stays on the server, keyed by a cookie, and is shared by every page the user visits until it expires.
Comparison
| ViewState | Session | |
|---|---|---|
| Stored | In the page (__VIEWSTATE hidden field) | On the server (memory, state service, SQL Server…) |
| Scope | One page, one browser tab | One user, all pages, all tabs |
| Lifetime | Until the user leaves the page | Until timeout (20 minutes idle by default) or Session.Abandon() |
| Cost | Bandwidth: sent down and posted back on every request | Server memory or storage, per active user |
| Visibility | Base64-encoded, signed (MAC) but readable unless encrypted | Not sent to the client; only a session id cookie |
| Types | Serialisable types; best kept to simple values | Any type in InProc; serialisable types out-of-process |
ViewState in code
// A page-level property backed by ViewState
private int SortColumn
{
get => (int)(ViewState["SortColumn"] ?? 0);
set => ViewState["SortColumn"] = value;
}
protected void lnkSortByPrice_Click(object sender, EventArgs e)
{
SortColumn = 2;
BindGrid();
}
Controls use view state too: it is how a GridView keeps its rows across postbacks without rebinding. Turn it off where it is not needed (EnableViewState="false", or ViewStateMode="Disabled" on a container) to shrink large pages.
Session in code
// Store
Session["CartId"] = cart.Id;
// Read, with a null check: the session may have expired
if (Session["CartId"] is int cartId)
{
LoadCart(cartId);
}
else
{
Response.Redirect("~/Cart/Empty.aspx", false);
Context.ApplicationInstance.CompleteRequest();
}
// End the session on logout
Session.Clear();
Session.Abandon();
Choosing
- Sort order, current page index, a selected tab, values needed only while the user stays on this page: ViewState.
- A shopping cart id, a multi-page wizard's progress, the user's display preferences during a visit: Session.
- Anything the user must not see or change (prices, permissions): neither as the source of truth. Recompute from the database; at most keep an id.
- Large objects: neither. Store a key and reload.
Security notes
- View state is protected against tampering by a MAC (always on since ASP.NET 4.5.2; never disable it). On a web farm, all servers need the same
<machineKey>. - Do not put secrets in view state; set
ViewStateEncryptionMode="Always"if a page must keep sensitive values there. - Session ids are bearer tokens: serve the site over HTTPS, mark cookies
SecureandHttpOnly, and regenerate the session after login. - Out-of-process session state needs serialisable objects; see Unable to serialize the session state.
Official documentation
- Microsoft Learn: ASP.NET state management overview
- Microsoft Learn: Control.ViewState, HttpSessionState
- Microsoft Learn: Page.ViewStateEncryptionMode