NET Centric Computing · Unit 6 · 4 hrs
State Management on ASP.NET Core Application
Exam-focused notes for State Management on ASP.NET Core Application (NET Centric Computing, CSC378): what the TU syllabus asks and how it has actually been tested, with 6 solved past questions from this unit.
State Management on ASP.NET Core Application in short
This unit deals with a fact that shapes every ASP.NET Core application: HTTP itself remembers nothing between requests, so the framework needs deliberate strategies to carry data forward, some stored on the server, some carried by the client.
What this unit covers
- State Management on stateless HTTP
- Server-side strategies: Session State, TempData, Using HttpContext, Cache
- Client-side strategies: Cookies, Query Strings, Hidden Fields
Client-side strategies
2081 · 5 marks
Define state management. Explain the parts of state management on the client side. [5]
Show solved answerHide answer
State Management in ASP.NET
Definition of State Management
State management is the process of preserving and maintaining the state (data/information) of a user or application across multiple HTTP requests. Since HTTP is a stateless protocol, each request is treated as independent and the server does not automatically remember previous interactions. State management techniques are used to overcome this limitation and retain data between requests, either on the client side or the server side.
ASP.NET Web Forms includes several options that help preserve data on both a per-page basis and an application-wide basis.
Client-Side State Management
In client-side state management, the state data is stored on the client's machine (browser) rather than on the server. This reduces server load but may have limitations in terms of security and data size.
The main parts of client-side state management are:
1. Cookies
Cookies store data directly in the user's browser. The browser automatically sends cookies with every HTTP request made to the server.
Key Points:
- Since cookies are sent with every request, their size should be kept to a minimum.
- Commonly used to personalize content for a known user, especially for identification without full authentication.
- Example: storing a user's name or preferred color theme.
Reading a Cookie:
// Read cookie from HttpContextAccessor
string cookieValueFromContext = HttpContextAccessor.HttpContext.Request.Cookies["key"];
// Read cookie from Request object
string cookieValueFromReq = Request.Cookies["key"];
Writing a Cookie:
public void SetCookie(string key, string value, int? expireTime)
{
CookieOptions option = new CookieOptions();
if (expireTime.HasValue)
option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
else
option.Expires = DateTime.Now.AddMilliseconds(10);
Response.Cookies.Append(key, value, option);
}
Removing a Cookie:
Response.Cookies.Delete(key);
2. Query Strings
A query string is a part of the URL that carries a limited amount of data from one request to another by appending it to the URL of the new request.
Key Points:
- Useful for capturing state in a persistent manner.
- Allows sharing of links with embedded state (e.g., bookmarking a filtered search result).
- Data is visible in the URL, so it is not suitable for sensitive information.
Example:
https://example.com/products?category=books&page=2
Here, category=books and page=2 are query string parameters that carry state between requests.
Summary Table
| Technique | Storage Location | Size Limit | Use Case |
|---|---|---|---|
| Cookies | Browser | Small | User preferences, personalization |
| Query Strings | URL | Very small | Page navigation, shareable links |
Both techniques are important client-side state management strategies in ASP.NET that help maintain user data across stateless HTTP requests without relying on server memory.
State Management on stateless HTTP
2080 · 10 marks
How do you manage state on stateless HTTP? How do you validate form using JQuery? Describe with your own assumptions.[10]
Show solved answerHide answer
Managing State on Stateless HTTP and Form Validation Using jQuery
Part 1: Managing State on Stateless HTTP (5 marks)
What is the Problem?
HTTP is a stateless protocol, meaning each request from a client to the server is independent. The server does not remember any previous request. However, real-world web applications (like shopping carts, login sessions, etc.) need to remember user data across multiple requests. This is called state management.
State Management Approaches in ASP.NET
The following storage approaches are used to manage state on stateless HTTP:
| Storage Approach | Description |
|---|---|
| Cookies | HTTP cookies. May include data using server-side app code. |
| Session State | HTTP cookies and server-side app code. |
| TempData | HTTP cookies or session state. |
| Query Strings | HTTP query strings. |
| Hidden Fields | HTTP form fields. |
| HTTP Content | Server-side app code. |
| Cache | Cache server-side app code. |
Detailed Explanation of Each Approach
1. Cookies
- Small pieces of data stored on the client's browser.
- Sent automatically with every HTTP request to the server.
- Used to remember user preferences, login tokens, etc.
// Setting a cookie in ASP.NET MVC
Response.Cookies.Append("Username", "JohnDoe");
// Reading a cookie
string username = Request.Cookies["Username"];
Limitation: Cookies can be tampered with by the client, so sensitive data should not be stored directly.
2. Session State
- Data is stored on the server side.
- A unique session ID is stored in a cookie on the client side.
- The server uses this ID to retrieve the corresponding session data.
// Storing data in session
HttpContext.Session.SetString("UserName", "JohnDoe");
// Retrieving data from session
string name = HttpContext.Session.GetString("UserName");
Advantage: More secure than cookies since actual data stays on the server.
3. TempData
- Used to pass data between two consecutive requests (e.g., from one action to another after a redirect).
- Internally uses cookies or session state.
// Storing in TempData
TempData["Message"] = "Record saved successfully!";
// Reading in the next request
string msg = TempData["Message"].ToString();
4. Query Strings
- Data is passed as part of the URL.
https://example.com/products?category=electronics&page=2
string category = Request.Query["category"];
Limitation: Visible in the URL, not suitable for sensitive data.
5. Hidden Fields
- Data is stored in HTML form fields that are not visible to the user but are submitted with the form.
<input type="hidden" name="UserId" value="101" />
Limitation: Can be viewed and modified by inspecting the page source.
6. Cache
- Data is stored server-side in memory for fast access.
- Suitable for data that is expensive to compute and shared across users.
// Using IMemoryCache
_cache.Set("ProductList", products, TimeSpan.FromMinutes(10));
Summary Diagram
Client (Browser) Server
| |
|--- HTTP Request (stateless) --->|
| |
| State managed via: |
| - Cookies (client-side) |
| - Session (server-side) |
| - TempData (redirect) |
| - Query Strings (URL) |
| - Hidden Fields (form) |
| - Cache (server memory) |
|<-- HTTP Response ---------------|
Part 2: Form Validation Using jQuery (5 marks)
What is jQuery Form Validation?
jQuery provides a simple and powerful way to validate HTML forms on the client side before the data is submitted to the server. This improves user experience by giving instant feedback without a page reload.
The most commonly used plugin is the jQuery Validation Plugin.
Assumptions
- We have a Student Registration Form with fields: Name, Email, Age, and Password.
- jQuery and jQuery Validation plugin are included via CDN.
- Validation is done client-side before form submission.
Step 1: HTML Form Structure
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
<!-- Include jQuery -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<!-- Include jQuery Validation Plugin -->
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.validate.min.js"></script>
<style>
.error { color: red; font-size: 12px; }
input { display: block; margin: 8px 0; padding: 5px; }
</style>
</head>
<body>
<h2>Student Registration Form</h2>
<form id="registrationForm">
<label>Full Name:</label>
<input type="text" id="name" name="name" placeholder="Enter your name" />
<label>Email:</label>
<input type="email" id="email" name="email" placeholder="Enter your email" />
<label>Age:</label>
<input type="number" id="age" name="age" placeholder="Enter your age" />
<label>Password:</label>
<input type="password" id="password" name="password" placeholder="Enter password" />
<label>Confirm Password:</label>
<input type="password" id="confirmPassword" name="confirmPassword"
placeholder="Confirm password" />
<button type="submit">Register</button>
</form>
</body>
</html>
Step 2: jQuery Validation Script
<script>
$(document).ready(function () {
$("#registrationForm").validate({
rules: {
name: {
required: true,
minlength: 3
},
email: {
required: true,
email: true
},
age: {
required: true,
number: true,
min: 16,
max: 100
},
password: {
required: true,
minlength: 6
},
confirmPassword: {
required: true,
equalTo: "#password"
}
},
messages: {
name: "Please enter your full name (at least 3 characters).",
email: "Please enter a valid email address.",
age: "Age must be between 16 and 100.",
password: "Password must be at least 6 characters long.",
confirmPassword: "Passwords do not match."
},
submitHandler: function (form) {
alert("Registration form is valid! Submitting...");
form.submit();
}
});
});
</script>
The jQuery Validation Plugin's .validate() call attaches a rules object (what each field must satisfy) and a matching messages object (what to show when a rule fails) directly to the form, and it re-checks every field automatically on blur and on keyup, so the student sees an inline error the moment a field becomes invalid, without any page reload. The submitHandler only fires once every rule passes, at which point the form is genuinely submitted to the server, giving the registration page instant client-side feedback backed by the plugin's built-in required, email, number, minlength, and equalTo validators.
2078 · 10 marks
What are the advantages of stateless HTTP in ASP.NET core application? Create a method to insert a record (3, 'John', 12000) onto the table Employee having fields EmployeeId(int), Name varchar(200), Salary(int) using Entity Framework.[10]
Server-side strategies
2076 · 5 marks
Explain about request object and session object in ASP.[5]
2076 · 5 marks
Differentiate between application object and server object in ASP.[5]
Make Unit 6 stick
Practice CSC378 with flashcards & quizzes