ASP.NET

Session state vs ViewState in ASP.NET

ASP.NET · · Published 2026-09-23

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

ViewStateSession
StoredIn the page (__VIEWSTATE hidden field)On the server (memory, state service, SQL Server…)
ScopeOne page, one browser tabOne user, all pages, all tabs
LifetimeUntil the user leaves the pageUntil timeout (20 minutes idle by default) or Session.Abandon()
CostBandwidth: sent down and posted back on every requestServer memory or storage, per active user
VisibilityBase64-encoded, signed (MAC) but readable unless encryptedNot sent to the client; only a session id cookie
TypesSerialisable types; best kept to simple valuesAny 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

Security notes

Official documentation