ASP.NET  

Difference Between Session, ViewState, QueryString, TempData, and More in ASP.NET

Introduction

In ASP.NET, managing state across web pages and requests is a common challenge. Since HTTP is stateless, developers use tools like Session, ViewState, QueryString, and others to maintain user data across pages or actions.

In this article, we'll explore the differences, use cases, advantages, and limitations of each major state management technique in ASP.NET (non-Core), with examples.

1. Session

What is it?

  • Stores user data on the server, tied to a specific user's session.

  • Data is preserved across multiple pages and requests.

How to use

Session["Username"] = "john.doe";
var name = Session["Username"].ToString();

Pros

  • Stores large amounts of data

  • Secure (data not exposed to client)

  • Persistent across all pages

Cons

  • Consumes server memory

  • Expires after timeout (default 20 mins)

  • Not suitable for storing sensitive data across long periods

Ideal for

  • Login information, cart items, user preferences

2. QueryString

What is it?

  • Passes data in the URL between pages using key-value pairs.

How to use

// URL: example.com/page.aspx?userId=123
string userId = Request.QueryString["userId"];

Pros

  • Easy to implement

  • Visible and editable (good for bookmarks, sharing)

Cons

  • Not secure (data exposed in URL)

  • Limited length (~2048 characters)

  • Can’t store complex objects

Ideal for

  • Passing non-sensitive data between pages

  • Pagination, search filters, IDs

3. ViewState

What is it?

  • Stores data on the client side, inside a hidden field on the page.

  • Maintains state within the same page during postbacks.

How to use

ViewState["Counter"] = 5;
int counter = Convert.ToInt32(ViewState["Counter"]);

Pros

  • Simple to use for postback data

  • No server memory usage

  • Automatic with ASP.NET controls

Cons

  • Increases page size

  • Not suitable for sensitive data

  • Only works for postbacks, not across pages

Ideal for

  • Form data, control values, small page-level values

4. TempData (Mostly in ASP.NET MVC)

What is it?

  • Stores data temporarily between two requests (like redirects).

  • Stored in Session internally.

How to use

TempData["Message"] = "User created!";
return RedirectToAction("Index");

// In next request:
string msg = TempData["Message"]?.ToString();

Pros

  • Great for redirect-after-post

  • Auto-clears after it’s read

Cons

  • Only survives one redirect

  • Overuse can lead to confusion

Ideal for

  • Showing success/error messages after form submissions

5. Hidden Fields

What is it?

  • A manual way to store data in forms that persists during postback.

How to use

<input type="hidden" id="HiddenField1" value="123" />

Pros

  • Works without ViewState

  • Useful in lightweight pages

Cons

  • Visible in source (can be tampered with)

  • Not secure

6. Cookies

What is it?

  • Stores small amounts of data in the user’s browser.

  • Can be persistent (saved for days) or session-based.

How to use

Response.Cookies["User"]["Name"] = "John";
string name = Request.Cookies["User"]["Name"];

Pros

  • Data persists even after the browser closes (if you set expiry)

  • Good for personalization

Cons

  • Limited to 4KB

  • Can be disabled by the browser

  • Visible to user (not secure)

Comparison Table

FeatureScopeStorageSecureExpiresSize LimitPage-to-Page
SessionPer-userServerβœ…YesLargeβœ…
ViewStateSingle pageClient❌NoMedium❌ (only postbacks)
QueryStringPer-requestClient❌No~2KBβœ…
TempDataAcross 1 requestServerβœ…YesLargeβœ… (1-time only)
Hidden FieldSingle pageClient❌NoSmall❌
CookiesBrowserClient❌Yes4KBβœ…

Conclusion

Choosing the right state management method in ASP.NET depends on:

  • Where you want to store the data (client/server)

  • How long do you want to keep it

  • How secure does the data need to be

If you're storing sensitive or large data, use Session.
For simple filters or IDs between pages β€” use QueryString.
For maintaining form data during postbacks β€” use ViewState.