ASP.NET

State and navigation in ASP.NET Web Forms: ViewState, Session, query strings, cross-page posts and breadcrumbs

ASP.NET · · Published 2026-11-29

HTTP forgets everything between two requests. Web Forms hides that with several stores and several ways of moving from page to page, each with its own lifetime and its own risks. ViewState keeps values inside one page's postbacks; Session keeps them for one user across pages; the query string carries them in the URL; cross-page posting hands a whole form to the next page. Around them, the site map describes where each page sits, and the page head tells browsers and search engines what each page is. This guide covers those mechanisms together, because choosing one is always a matter of comparing it with the others.

Where should this value live?

StoreLifetimeVisible to the user?Good for
ViewStatePostbacks of one pageEncoded, signed, not encrypted by defaultSmall UI state (sort column, selected keys)
SessionOne user, until timeoutNo (server side)Cart, wizard data, user preferences
Query stringOne URLYes, and shareableIds, filters, page numbers
Cross-page postOne requestForm fieldsSearch forms posting to a results page

Session state vs ViewState

The two stores developers confuse most often come first.

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

Reading query string values in the browser

The query string is the most visible store: the server reads it with Request.QueryString, the browser with URLSearchParams.

Scripts often need a value from the page URL: orders.aspx?status=open&page=2. ASP.NET reads it with Request.QueryString on the server; in the browser, the standard URLSearchParams object does the same job, decoding included. jQuery has no helper for it and does not need one.

URLSearchParams

// URL: /orders.aspx?status=open&page=2&tag=a&tag=b&q=caf%C3%A9+cr%C3%A8me
var params = new URLSearchParams(window.location.search);

params.get("status");     // "open"
params.get("page");       // "2" (always a string)
params.get("missing");    // null
params.has("status");     // true
params.getAll("tag");     // ["a", "b"]
params.get("q");          // "café crème" (+ and %XX are decoded)

var page = parseInt(params.get("page"), 10) || 1;

Values are strings; convert them and supply defaults. getAll handles repeated keys, which get reduces to the first value.

Using it with jQuery

$(function () {
  var status = new URLSearchParams(location.search).get("status") || "all";
  $("#statusFilter").val(status);
  $(".tab[data-status='" + CSS.escape(status) + "']").addClass("active");
});

CSS.escape protects the selector against characters such as quotes in the value. Never write a query string value into the page with .html(): use .text() or .val(), or you create a cross-site scripting hole.

Older code: the regular-expression helper

Before URLSearchParams (supported by all current browsers, not by Internet Explorer), tutorials used a function like this. You will meet it in existing projects:

function getQueryValue(name) {
  var escaped = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  var m = new RegExp("[?&]" + escaped + "=([^&#]*)").exec(location.search);
  return m ? decodeURIComponent(m[1].replace(/\+/g, " ")) : null;
}

Note the + replacement: in query strings produced by forms, a space is encoded as +, which decodeURIComponent alone does not convert.

Building a URL with parameters

var p = new URLSearchParams({ status: "open", page: 3 });
location.href = "orders.aspx?" + p.toString();   // status=open&page=3, encoded

The server decides

Anything a script reads from the URL, the server reads too, and the user can edit both. Use client-side values for display only, and validate them in the code-behind as shown in Passing multiple QueryString parameters. Values after # are a different part of the URL: see Read the URL hash.

Updating the URL without reloading

When a filter changes on the page, you can keep the URL in sync so that refreshing or sharing it restores the same view:

var params = new URLSearchParams(location.search);
params.set("status", "closed");
params.delete("page");
history.replaceState(null, "", location.pathname + "?" + params.toString());

replaceState changes the address bar without a new request or history entry; use pushState if the back button should return to the previous filter.

Encoding values in a query string, ampersands included

Building a URL is where query strings break: a value containing &, # or a space must be encoded.

The ampersand separates parameters in a query string. Put Tom & Jerry into a URL as it is and the server sees a parameter title=Tom plus a stray parameter named Jerry. The value must be URL-encoded, so the & travels as %26.

The problem

string title = "Tom & Jerry";
Response.Redirect("Search.aspx?title=" + title);   // wrong
// URL: Search.aspx?title=Tom & Jerry
// Request.QueryString["title"] on the next page: "Tom " (and a key " Jerry")

Other characters cause similar trouble: # starts the fragment and is never sent to the server, + is decoded as a space, = and % confuse parsing.

Encoding in C#

string url = "Search.aspx?title=" + HttpUtility.UrlEncode(title);
// Search.aspx?title=Tom+%26+Jerry

string url2 = "Search.aspx?title=" + Uri.EscapeDataString(title);
// Search.aspx?title=Tom%20%26%20Jerry

Both are correct. HttpUtility.UrlEncode uses + for spaces (form encoding); Uri.EscapeDataString uses %20. ASP.NET decodes both forms. Encode each value separately, never the whole URL, or the ?, = and & that structure it would be encoded too.

For several parameters, HttpUtility.ParseQueryString(string.Empty) builds and encodes the whole query, as shown in Passing multiple QueryString parameters.

Reading it

string title = Request.QueryString["title"];   // "Tom & Jerry", already decoded

Do not call UrlDecode again: decoding twice turns a literal %26 typed by the user into an ampersand and a literal + into a space.

In markup

<asp:HyperLink runat="server"
    NavigateUrl='<%# "Search.aspx?title=" + HttpUtility.UrlEncode((string)Eval("Title")) %>'
    Text='<%#: Eval("Title") %>' />

Two different encodings meet here. The URL value is URL-encoded (%26). The link as a whole is then written into an HTML attribute, where the separator between parameters should be written &amp;; the HyperLink control handles that HTML encoding for you. When writing an <a href> by hand with two parameters, write ?a=1&amp;b=2 in the HTML source; browsers tolerate a bare & in most cases, but the escaped form is always valid.

In JavaScript

var url = "Search.aspx?title=" + encodeURIComponent("Tom & Jerry"); // Tom%20%26%20Jerry
// or let the browser do it:
var p = new URLSearchParams({ title: "Tom & Jerry", page: 2 });
location.href = "Search.aspx?" + p;   // title=Tom+%26+Jerry&page=2

Use encodeURIComponent, not encodeURI: the latter leaves &, = and ? unencoded because it is meant for whole URLs. Reading values on the client is covered in Read a QueryString value in the browser.

Common mistakes

Cross-page posting and PreviousPage

When a whole form should go to another page, cross-page posting avoids squeezing it into a URL.

Normally a Web Forms page posts back to itself. With cross-page posting, a button sends the form to a different page, which can then read the first page's controls through PreviousPage. It is a tidy way to build a search form whose results live on another page, without putting everything in the URL.

The source page

<%-- Search.aspx --%>
<asp:TextBox ID="txtTerm" runat="server" />
<asp:DropDownList ID="ddlScope" runat="server">
    <asp:ListItem Value="all">Everything</asp:ListItem>
    <asp:ListItem Value="docs">Documents only</asp:ListItem>
</asp:DropDownList>
<asp:Button ID="btnSearch" runat="server" Text="Search" PostBackUrl="~/Results.aspx" />

Expose the values through public properties in the code-behind, so the target page does not need to know control ids:

public partial class Search : Page
{
    public string Term => txtTerm.Text.Trim();
    public string Scope => ddlScope.SelectedValue;
}

The target page, strongly typed

<%@ Page Language="C#" CodeBehind="Results.aspx.cs" Inherits="Demo.Results" %>
<%@ PreviousPageType VirtualPath="~/Search.aspx" %>
public partial class Results : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (PreviousPage != null && PreviousPage.IsCrossPagePostBack)
        {
            string term = PreviousPage.Term;   // typed as Demo.Search thanks to @PreviousPageType
            string scope = PreviousPage.Scope;
            lblInfo.Text = "Results for " + Server.HtmlEncode(term);
            RunSearch(term, scope);
        }
        else if (!IsPostBack)
        {
            Response.Redirect("~/Search.aspx", false);
            Context.ApplicationInstance.CompleteRequest();
        }
    }
}

When you read PreviousPage, ASP.NET creates an instance of Search, runs its life cycle up to LoadComplete with the posted data, and hands it to you. Its controls contain the values the user submitted. Validation has run on the source page too, so you can check PreviousPage.IsValid.

Without the directive: FindControl

if (PreviousPage != null)
{
    var box = (TextBox)PreviousPage.FindControl("txtTerm");
    string term = box?.Text;
}

If the source uses a master page, the controls sit inside a ContentPlaceHolder, and PreviousPage.FindControl will not find them directly: look them up through PreviousPage.Master.FindControl("MainContent").FindControl("txtTerm"). Public properties avoid this fragility.

Comparison

TechniqueURL in the browserData
Cross-page postThe target pageFull form posted to the target
Server.TransferStill the source pagePreviousPage also available, no new request
Query stringTarget page with parameters, bookmarkableA few short values
SessionAnyKept server-side across many requests

A cross-page post is a POST: refreshing the results page asks the browser to resend the form, and the results cannot be bookmarked. For a search page that users share, the query string is usually better.

Common mistakes

Navigation is also about showing users where they are.

A breadcrumb shows where the current page sits in the site: Home › Products › Training. In Web Forms the SiteMapPath control builds it automatically from the same Web.sitemap file that can feed a Menu control.

Web.sitemap

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">
  <siteMapNode url="~/Default.aspx" title="Home">
    <siteMapNode url="~/Products/Default.aspx" title="Products">
      <siteMapNode url="~/Products/Training.aspx" title="Training" />
      <siteMapNode url="~/Products/Software.aspx" title="Software" />
    </siteMapNode>
    <siteMapNode url="~/Contact.aspx" title="Contact" />
  </siteMapNode>
</siteMap>

The file must be called Web.sitemap and sit at the application root for the default provider to find it. Each URL may appear only once.

The control in a master page

<nav aria-label="Breadcrumb" class="crumbs">
    <asp:SiteMapPath ID="smpTrail" runat="server" PathSeparator=" › "
        RenderCurrentNodeAsLink="false" ShowToolTips="false" />
</nav>

On ~/Products/Training.aspx it renders Home › Products › Training, with the first two as links. The control finds the current node by comparing the request URL with the site map; on a page that is not in the file, it renders nothing.

Templates for cleaner markup

By default the control renders spans. Templates let you output what you want, including aria-current on the last item:

<asp:SiteMapPath ID="smpTrail" runat="server" PathSeparator="">
    <NodeTemplate>
        <a href='<%# Eval("Url") %>'><%#: Eval("Title") %></a> ›
    </NodeTemplate>
    <CurrentNodeTemplate>
        <span aria-current="page"><%#: Eval("Title") %></span>
    </CurrentNodeTemplate>
</asp:SiteMapPath>

In the templates, the data item is the SiteMapNode, so Eval("Url") returns an already resolved URL and Eval("Title") the title. A RootNodeTemplate also exists if the home link needs its own look.

Pages with query strings

Product.aspx?id=42 is one URL in the site map but many products. Handle the provider's SiteMapResolve event to build a node for the current item on the fly:

// Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
    SiteMap.SiteMapResolve += (s, args) =>
    {
        if (!args.Context.Request.Path.EndsWith("/Product.aspx", StringComparison.OrdinalIgnoreCase))
            return null; // fall back to normal behaviour

        SiteMapNode parent = SiteMap.Provider.FindSiteMapNode("~/Products/Default.aspx");
        if (parent == null) return null;

        int.TryParse(args.Context.Request.QueryString["id"], out int id);
        string name = ProductRepository.Find(id)?.Name ?? "Product";

        var current = new SiteMapNode(SiteMap.Provider, "product-" + id,
                                      args.Context.Request.RawUrl, name);
        current.ParentNode = parent.Clone(true);
        return current;
    };
}

The cloned parent keeps the original tree intact. Remember to encode the product name when it is displayed; the template above does that with <%#: %>.

Style

.crumbs { font-size: .9rem; margin: .5rem 0 1rem; }
.crumbs a { color: #1b6aa5; }
.crumbs [aria-current] { color: #555; }

Structured data

Search engines can show breadcrumbs instead of a raw URL in results if the page includes BreadcrumbList structured data (JSON-LD) that matches the visible trail. Generate it from the same nodes: walk from SiteMap.CurrentNode up through ParentNode, then output the list in order with absolute URLs.

Page title, description and meta tags from code

Each page should finally describe itself correctly in its head, especially pages built from database content.

Pages that display database content, such as a product or an article, need a title and description built from that content. Since .NET 4, Web Forms makes this a one-liner per tag, as long as the page has a <head runat="server">.

Requirement: a server-side head

<head runat="server">
    <title></title>
</head>

Without runat="server", Page.Header is null and the properties below have nothing to write into. With master pages, the <head runat="server"> lives in the master page, and content pages can still set the values.

Title, description and keywords

protected void Page_Load(object sender, EventArgs e)
{
    if (!int.TryParse(Request.QueryString["id"], out int id)) { ShowNotFound(); return; }

    Product p = ProductRepository.Find(id);
    if (p == null) { ShowNotFound(); return; }

    Page.Title = p.Name + " | Example Shop";
    Page.MetaDescription = Shorten(p.Summary, 155);
    Page.MetaKeywords = string.Join(", ", p.Tags); // optional, see below
}

private static string Shorten(string text, int max)
{
    if (string.IsNullOrEmpty(text) || text.Length <= max) return text ?? "";
    int cut = text.LastIndexOf(' ', max);
    return text.Substring(0, cut > 0 ? cut : max) + "…";
}

private void ShowNotFound()
{
    Response.StatusCode = 404;
    Page.Title = "Product not found";
}

ASP.NET HTML-encodes these values when it renders them, so quotes or angle brackets in a product name cannot break the markup. MetaDescription and MetaKeywords render <meta name="description"> and <meta name="keywords">; if the markup already contains such tags, the property replaces their content.

You can also set them declaratively in the @Page directive: <%@ Page Title="Contact" MetaDescription="How to reach us" %>.

Other tags: canonical, Open Graph, robots

HtmlMeta and HtmlLink controls add anything else:

using System.Web.UI.HtmlControls;

var canonical = new HtmlLink { Href = "https://www.example.com/products/" + p.Slug };
canonical.Attributes["rel"] = "canonical";
Page.Header.Controls.Add(canonical);

var ogTitle = new HtmlMeta();
ogTitle.Attributes["property"] = "og:title";  // Open Graph uses "property", not "name"
ogTitle.Content = p.Name;
Page.Header.Controls.Add(ogTitle);

if (p.IsHidden)
{
    Page.Header.Controls.Add(new HtmlMeta { Name = "robots", Content = "noindex" });
}

Adding controls to the header fails with "The Controls collection cannot be modified because the control contains code blocks" if the <head> contains <%= … %> expressions. Replace them with data-binding expressions (<%# … %>) and call Page.Header.DataBind(), or move scripts out of the head.

What search engines use

The full server-side treatment of query strings, with several parameters and validation, is in passing multiple query string parameters. Moving session state out of process raises its own error, explained in Unable to serialize the session state.

Checklist

Sources