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
Ideal for
2. QueryString
What is it?
How to use
// URL: example.com/page.aspx?userId=123
string userId = Request.QueryString["userId"];
Pros
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
Cons
Ideal for
4. TempData (Mostly in ASP.NET MVC)
What is it?
How to use
TempData["Message"] = "User created!";
return RedirectToAction("Index");
// In next request:
string msg = TempData["Message"]?.ToString();
Pros
Cons
Ideal for
5. Hidden Fields
What is it?
How to use
<input type="hidden" id="HiddenField1" value="123" />
Pros
Cons
6. Cookies
What is it?
How to use
Response.Cookies["User"]["Name"] = "John";
string name = Request.Cookies["User"]["Name"];
Pros
Cons
Comparison Table
Feature | Scope | Storage | Secure | Expires | Size Limit | Page-to-Page |
---|
Session | Per-user | Server | β
| Yes | Large | β
|
ViewState | Single page | Client | β | No | Medium | β (only postbacks) |
QueryString | Per-request | Client | β | No | ~2KB | β
|
TempData | Across 1 request | Server | β
| Yes | Large | β
(1-time only) |
Hidden Field | Single page | Client | β | No | Small | β |
Cookies | Browser | Client | β | Yes | 4KB | β
|
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.