2080 1

CSC378 ยท 2080 ยท 10 marks

How do you manage state on stateless HTTP? How do you validate form using JQuery? Describe with your own assumptions.

How do you manage state on stateless HTTP? How do you validate form using JQuery? Describe with your own assumptions.[10]

NET Centric ComputingChapter 6: State Management on ASP.NET Core ApplicationState Management on stateless HTTP

Quick answer

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.

Managing State on Stateless HTTP and Form Validation Using jQuery

Part 1: Managing State on Stateless HTTP (5 marks)

What is the Problem?


State Management Approaches in ASP.NET

The following storage approaches are used to manage state on stateless HTTP:

Storage ApproachDescription
CookiesHTTP cookies. May include data using server-side app code.
Session StateHTTP cookies and server-side app code.
TempDataHTTP cookies or session state.
Query StringsHTTP query strings.
Hidden FieldsHTTP form fields.
HTTP ContentServer-side app code.
CacheCache 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.

Short on time? The 1, 5 and 10 mark versions of this answer, flashcards and practice sets come with a program pass.