CsitLabs
  • CSIT Labs
  • 1st Semester
    • Digital Logics
      • Lab 1
      • Lab 2
      • Lab 3
      • Lab 4
      • Lab 5
      • Lab6
    • IIT
    • Physics Lab Report Formet
  • 2nd Semester
    • Algorithms used in Discrete Structure class
    • Microprocessor
      • 8085 Microprocessor
        • Arithmetic and Logical Instruction Set
        • Branching Instruction Set
        • Data Transfer and Instruction Set
        • Multiply, Divide and Memory Block Operations
        • Rotate Instruction Set
        • Subroutine, Stack and BCD Conversion](Subroutine_Stack_BCD_Conversion
      • 8086 Microprocessor
        • Basic Arithmetic
        • Practice Programs for 8086 Microprocessor
        • String Processing
    • Object Oriented Programming using C++
      • File Access Pointers
      • Standard Exceptions in C++
    • Statistics-I
  • 3rd Semester
    • Computer Architecture
      • Practical labs
    • Computer Graphics
      • Practial
      • Simulation of Two Dimensional Transformation
      • Scan Conversion Algorithm
    • Data Structures and Algorithms
      • Array methods (Introduction)
      • Stack
      • Queue
      • Recursion
      • Linked List
      • Sorting Algorithms
      • Searching and Hashing Algorithms
      • Trees and Graphs
      • Lab practice
    • Numerical Method Labs
      • Lab practice
    • Statistics-II Labs
      • Confidence interval of mean assuming normal distribution
      • One Sample T test
      • Two Sample T test
      • Regression Analysis
      • Two Sample T test
      • Design_of_Experiment
        • CRD (Completely Randomized Design)
        • RBD (Randomized Block Design)
        • RBD (Randomized Block Design)
      • Non-parametric_test
        • Binomial Test
        • Cochran Q test
        • Kolmogorov-Smirnov one sample test
        • Run test
        • Friedman-F_test
          • Friedman F test
          • Friedman F test
        • Kruskal-Wallis-H_test
          • Kruskal Wallis H test
          • Kruskal Wallis H test
        • Mann-Whitney-U_test
          • Mann Whitney U test
          • Mann Whitney U test
        • Median_test
          • Median Test
          • Median Test
        • Wilcoxon-Matched-pair_signed_rank_test
          • Wilcoxon Matched pair signed rank test
          • Wilcoxon Matched pair signed rank test
  • 4th Semester
    • Artificial Intelligence
    • Computer Networks
      • Networking commands in CMD
    • DBMS Lab
    • Operating System
      • Linux Commands
    • Theory of Computation
      • Lab 1 (DFA)
      • Lab 2 (NFA)
  • 5th Semester
    • Cryptography
    • Design and Analysis of algorithms
    • Multimedia
      • Animation Creation with Blender
      • FL Studio - Simple Effect Creation
      • Macromedia FreeHand - Logo Creation
      • Audio Mixing
      • Adobe Photoshop - ID Card Creation
      • Video Editing with Adobe Premiere Pro
    • Simulation & Modeling
      • Lab 1: Random Number Generation
    • System Analysis and Design
    • Web Technology
      • Lab Assignment – I (HTML)
      • Lab Assignment – II (CSS)
      • Lab Assignment – III (JavaScript and XML)
      • Lab Assignment – IV (PHP)
      • Web Technology
        • php
          • Database connection using PHP and MySQL
          • Login form
          • Login form
  • 6th Semester
    • Compiler Design and Construction
    • NET Centric Computing
      • Class Codes
        • Authentication and Authorization in ASP.NET
        • C# Basics
      • Lab Codes
        • Practical 1
        • Practical 2
          • Number Operations Web App
          • User Registration Form
          • User Registration Console App
        • Practical 3
          • Authentication and Authorization (Claims, Roles and Policies)
          • Client side state management in ASP.NET
          • Entity Framework Core
          • Form Validation
            • React form validation
          • HTML Tag Helpers
          • MVC demonstration
          • Razor Syntax
          • Server Side State Management in ASP.NET
      • Self Projects
        • Do while programs
        • Role playing game battle challenge
        • Project overview
        • Authentication
          • wwwroot
            • lib
              • jquery-validation
                • The MIT License (MIT)
  • 7th Semester
    • Advanced Java Programming
      • Class Codes
        • Unit1-6&8
          • javafx-sdk-21.0.1
            • legal
              • javafx.graphics
                • Independent JPEG Group (IJG) JPEG v9e
                • Mesa 3-D Graphics Library v21.0.3
              • javafx.media
                • Microsoft DirectShow Samples v156905
                • GNU Glib v2.72.0
                • GStreamer v1.20.1
                • LibFFI v3.4.4
              • javafx.web
                • IBM International Components for Unicode (ICU4C) v73.1
                • xmlsoft.org: libxml2 v2.10.4
                • xmlsoft.org: libxslt v1.1.35
                • WebKit Open Source Project: WebKit v616.1
          • src
            • main
              • java
                • Unit 1: Programming in Java
                  • 2. Concepts and Topics
                • Unit 2: User Interface Components with Swing
                • Unit 3: Event Handling
                • Unit 4: Database Connectivity
                • Unit 5: Network Programming
                • Unit 6: GUI with JavaFX
        • Unit7
          • src
            • main
              • webapp
                • index
      • Lab Codes
        • Lab
          • src
            • main
              • java
                • Practical 1
                • Practical 2
                • Practical 3
                • Practical 4
                • Practical5
    • Data warehouse and Data mining
  • docs
    • Contributor Covenant Code of Conduct
Powered by GitBook
On this page
  • Cookies
  • Reading Cookies
  • Writing Cookies
  • Removing Cookies
  • Query Strings
  • Accessing Query Strings
  • Hidden Fields

Was this helpful?

  1. 6th Semester
  2. NET Centric Computing
  3. Lab Codes
  4. Practical 3

Client side state management in ASP.NET

Client side state management is a technique used to store the state of a web page in the client's browser. This technique is used to maintain the state of a web page across multiple requests without storing the state on the server. This can help improve the performance of the web application by reducing the load on the server and reducing the amount of data that needs to be transferred between the client and the server.

In ASP.NET, there are several ways to manage the state of a web page on the client side. Some of the common ways are:

  • Cookies: Cookies are small pieces of data that are stored on the client's browser. They can be used to store information about the user, such as their preferences or login information.

  • Query Strings: Query strings are used to pass information between pages in a web application. They are appended to the URL of a page and can be read by the server-side code.

  • Hidden Fields: Hidden fields are used to store information on a web page that is not visible to the user. They are rendered as HTML input elements with the type="hidden" attribute.

    Example of hidden field:

    <input asp-for="userid" type="hidden" />

    Here, userid is the name of the hidden field and the value is stored in the value attribute.

Cookies

Cookies store data in the user's browser. Browsers send cookies to the server with each request, allowing the server to identify the user and maintain their state across multiple requests, so their size must be kept to minimum. Cookies can be set to expire after a certain period of time or when the browser is closed.

Users can easily tamper or delete a cookie, so we should not store sensitive information in cookies.

We often use cookies to personalize the content for a known user especially when we identify a user without identification. For example, we can store the user's name in a cookie so that we can display a personalized greeting message when the user visits the site, or a color theme preference.

Example of cookie:

Name: username
Value: John
Expiry: 2022-12-31

Here, username is the name of the cookie, John is the value, and 2022-12-31 is the expiry date.

Reading Cookies

// using IHttpContextAccessor
string cookieValueFromContext = httpContextAccessor.HttpContext.Request.Cookies["username"];

OR

// read cookie from request object
string cookie = Request.Cookies["username"];

Writing Cookies

public void SetCookie(string key, string value, int? expireTime)
{
    // create cookie options
    CookieOptions option = new CookieOptions();
    if (expireTime.hasValue)
    {
        option.Expires = DateTime.Now.AddMinutes(expireTime.Value);
    }
    else
    {
        // if no expiry time is specified, set the cookie to expire in 1 minute
        option.Expires = DateTime.Now.AddMinutes(1);
    }
    Response.Cookies.Append(key, value, option);
    return RedirectToAction("Index");
}

Removing Cookies

public void DeleteCookie(string key)
{
    Response.Cookies.Delete(key);
    return RedirectToAction("Index");
}

Query Strings

Query strings are used to pass information between pages in a web application. We can pass limited amount of data from one request to another by adding it to query string of new request. This is useful for capturing the state in a persistent manner and allows the sharing of links with the embedded state.

We should never use query strings for sensitive information as they are visible to the user and can be easily tampered with.

Note: In addition to unintended sharing, including data in query strings will make our application to Cross-Site Forgery(CSRF) attacks, which can trick users into visiting malicious sites while authenticated. Attackers can then steal user data or take malicious actions on behalf of the user.

Example in URL: http://www.example.com/page.aspx?name=John&age=25

Here, name=John&age=25 is the query string, where name and age are the keys and John and 25 are the values.

Accessing Query Strings

public String GetQueryString(string name, int age)
{
    return "Name: " + name + ", Age: " + age;
}

OR, passing data to Razor view using ViewBag:

public IActionResult Index(string name, int age)
{
    ViewBag.Name = name;
    ViewBag.Age = age;
    return View();
}
<p>Name: @ViewBag.Name</p>
<p>Age: @ViewBag.Age</p>

Hidden Fields

Hidden fields are used to store information on a web page that is not visible to the user. They are rendered as HTML input elements with the type="hidden" attribute.

We can save data in hidden form fields and send back in the next request. Sometimes we require some data to be stored on the client side without displaying it in the page. Later when the user takes action, we will need that data to be passed on the server side. In such cases, we can use hidden fields.

  • Index controller action method:

public IActionResult Index()
{
    ViewBag.Id = 1;
    ViewBag.Name = "John";
    return View();
}
[HttpPost]
public IActionResult Index(int Id, string Name)
{
    ViewBag.Id = Id;
    ViewBag.Name = Name;
    Console.WriteLine("Id: " + Id + ", Name: " + Name); // even if hidden field is not visible, we can access it
    return View();
}
  • The razor view:

<p>Hidden Field: @ViewBag.Id</p>

<form asp-action="Index" method="post">
  <input type="hidden" id="Id" name="Id" value="@ViewBag.Id" />
  <label for="Name">Name:</label>
  <input type="text" id="Name" name="Name" value="@ViewBag.Name" />
  <button type="submit">Submit</button>
</form>
PreviousAuthentication and Authorization (Claims, Roles and Policies)NextEntity Framework Core

Last updated 8 months ago

Was this helpful?