✅ State Management in ASP.NET
🔷 What is State Management?
State Management in ASP.NET is the technique used to store and retrieve user data (state) between HTTP requests.
⚠ HTTP is a stateless protocol — each request is independent, and the server does not remember any previous interaction.
So, to preserve data (like user login, shopping cart, form entries) across requests or pages, state management is used.
🔷 Types of State Management
ASP.NET provides two broad categories of state management:
| Type | Description |
|---|---|
| Client-Side | Stores data on the user's browser |
| Server-Side | Stores data on the server memory or backend |
🔷 1. Client-Side State Management
🔹 a. ViewState
- Stores data in hidden fields on the page.
- Used to preserve form values between postbacks.
- Data is stored in Base64 format in the HTML.
ViewState["username"] = "Praveen";
string name = ViewState["username"].ToString();
✅ Easy to use ❌ Increases page size
🔹 b. Hidden Fields
- Hidden HTML input that stores data not visible to users.
<input type="hidden" id="Hidden1" value="123" />
✅ Simple ❌ Can be tampered with
🔹 c. Cookies
- Stores small pieces of data (usually less than 4 KB) in the user's browser.
- Can be persistent (saved on disk) or session-based.
Response.Cookies["user"].Value = "Praveen";
string user = Request.Cookies["user"].Value;
✅ Can persist across sessions ❌ May be blocked by browsers
🔹 d. Query Strings
- Passes data in the URL.
Response.Redirect("Page2.aspx?name=Praveen");
✅ Simple and visible ❌ Not secure (exposed in URL), limited data
🔷 2. Server-Side State Management
🔹 a. Session State
- Stores data per user session on the server.
- Data is lost when the session expires.
Session["email"] = "praveen@email.com";
✅ Secure and server-side ❌ Can consume a lot of server memory for many users
🔹 b. Application State
- Shared data accessible by all users of the application.
Application["appName"] = "MyApp";
✅ Useful for global data ❌ Shared across users, potential concurrency issues
🔷 Comparison Table
| Method | Stored Where | Scope | Size Limit | Persistency |
|---|---|---|---|---|
| ViewState | Client (page) | Page only | Medium | Page reload only |
| Hidden Field | Client (page) | Page only | Small | Page reload only |
| Cookies | Client (browser) | All pages | \~4 KB | Optional persistent |
| QueryString | Client (URL) | Redirect pages | Small | Per URL |
| Session | Server | Per user session | Large | Session only |
| Application | Server | All users | Large | Until app restarts |
✅ Summary
- State Management helps maintain user-specific or application-wide data across web requests.
- Choose method based on security, data size, lifetime, and scope.
| Use Case | Best Choice |
|---|---|
| Preserve form data on postback | ViewState |
| Store global settings | Application State |
| Track logged-in user | Session |
| Pass data between pages | Query String or Cookies |
✅ Application Data Caching in ASP.NET
🔷 What is Caching?
Caching is the technique of storing frequently accessed data in memory so that future requests for that data can be served faster without recomputing or reloading it from the database or external resources.
In ASP.NET, application data caching improves performance and reduces server load.
🔷 Types of Caching in ASP.NET
- Output Caching – Caches whole pages
- Fragment Caching – Caches parts (controls) of pages
- Data Caching (Application Caching) – Caches application-level data like query results or computed values (our focus)
🔶 Application Data Caching (Data Caching)
📌 Definition:
Application Data Caching is a server-side mechanism used to store and reuse data objects (like datasets, lists, or strings) across user sessions.
🔷 Using Cache Object
ASP.NET provides a built-in Cache object to store key-value pairs in memory.
✅ Syntax:
Cache["KeyName"] = value; // Store in cache
var data = Cache["KeyName"]; // Retrieve from cache
🔷 Example:
if (Cache["ProductList"] == null)
{
DataTable products = GetProductsFromDatabase(); // Simulated method
Cache["ProductList"] = products; // Store in cache
}
DataTable cachedProducts = (DataTable)Cache["ProductList"];
✅ Next time the page loads, it won’t query the database again.
🔷 Cache with Expiration
a) Absolute Expiration
Cache expires after a fixed time, regardless of use.
Cache.Insert("Report", reportData, null, DateTime.Now.AddMinutes(10), TimeSpan.Zero);
b) Sliding Expiration
Cache expires if not used for a specific time.
Cache.Insert("Report", reportData, null, Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5));
🔷 Cache Dependencies
You can invalidate cache when a file or database value changes.
Cache.Insert("Data", obj, new CacheDependency(Server.MapPath("~/data.xml")));
✅ Useful to keep cached data in sync with the file.
🔷 Removing Cache
Cache.Remove("ProductList");
🔷 Advantages of Application Caching
| Benefit | Explanation |
|---|---|
| 🚀 Better Performance | Avoids repeated database hits |
| 🧠 Memory Based | Fast access to cached objects |
| ⌛ Flexible Expiry | Can expire data automatically |
| 📊 Scalability | Reduces server and DB load |
🔷 When to Use
- Caching lookup tables, frequent queries, config data
- Storing session-independent data across users
- Improving performance in data-heavy apps
✅ Summary
- Application caching stores reusable data in memory using the
Cacheobject. - Supports time-based expiration, dependencies, and manual removal.
- Improves speed and scalability of ASP.NET applications.