2081

CSC378 · TU past paper

NET Centric Computing 2081 question paper

The complete TU 2081 exam paper for NET Centric Computing (CSC378), all 12 questions with solved model answers written to the mark scheme.

Tap a question to open its answer.

  1. 110 marksAttributesAnswer

    Distinguish between collection and generics. What are named and positional attribute parameters? Write a program to create your own exception when the user gives subject name than 'C#'.[10]

    --- Basis Collection Generics --------- Namespace System.Collections System.Collections.Generic Type Safety Not type-safe; stores objects of any type Type-safe; stores objects of a specific type Data Type Works with object type (non-gene...

  2. 210 marksControllers and ActionsAnswer

    How do you create controller? Illustrate with an example. Describe the procedure of rendering HTML with Razor with scenario.[10]

    "Controller handles the user request. Typically the user uses the view, processes request and raises an HTTP request. Controller is the request handler." A Controller is a C class that: - Handles incoming HTTP requests - Interacts with t...

  3. 310 marksADO.NET basicsAnswer

    List some advantages of Entity Framework over ADO.NET. Assume a database named 'IOST' with a table FACULTY(Course_Name, CourseID, No_of_Semester, fee). Insert some records using ADO.NET and retrive the fee of records having name CSIT.[10]

    Entity Framework vs ADO.NET and ADO.NET Database Operations


    Part 1: Advantages of Entity Framework over ADO.NET

    Entity Framework (EF) is an Object/Relational Mapping (O/RM) framework that is an enhancement to ADO.NET giving developers an automated mechanism for accessing and storing data in the database.

    #Advantage of Entity FrameworkADO.NET Limitation
    1Automated Data Access: EF provides automated mechanism for accessing and storing data; no need to write raw SQL queries manuallyADO.NET requires writing explicit SQL queries for every operation
    2O/RM Support: Maps database tables directly to C# classes (domain objects), so developers work with objects instead of tablesADO.NET works at a lower level with DataReaders, DataSets, and manual mapping
    3Cross-Platform: EF Core is open-source, lightweight, extensible and cross-platformADO.NET has limited cross-platform support
    4Two Development Approaches: Supports Code-First and Database-First approaches giving flexibility in designADO.NET does not support code-first or migration-based schema generation
    5Migration Support: In Code-First, EF Core API creates the database and tables using migration based on conventions and configuration in domain classesADO.NET requires manual creation and management of database schema
    6Less Boilerplate Code: CRUD operations require significantly fewer lines of code using EFADO.NET requires verbose code (connection, command, reader, etc.) for every operation
    7Domain Driven Design (DDD): Code-First approach is useful in DDD, making it suitable for enterprise applicationsADO.NET is not aligned with DDD principles
    8Works with .NET Core and .NET 4.5+: EF Core is intended for .NET Core but also supports standard .NET 4.5+ applicationsADO.NET is primarily tied to the traditional .NET framework

    Part 2: ADO.NET - Insert Records and Retrieve Fee for CSIT

    Database Setup Assumption

    • Database Name: IOST
    • Table: FACULTY(Course_Name, CourseID, No_of_Semester, fee)

    Step 1: Create the Table in SQL Server (for reference)

    CREATE DATABASE IOST;
    
    USE IOST;
    
    CREATE TABLE FACULTY (
        Course_Name    VARCHAR(100),
        CourseID       INT PRIMARY KEY,
        No_of_Semester INT,
        fee            DECIMAL(10, 2)
    );
    

    Step 2: Full ADO.NET C# Code - Insert Records and Retrieve Fee for CSIT

    using System;
    using System.Data;
    using System.Data.SqlClient;
    
    namespace IOSTFacultyApp
    {
        class Program
        {
            // Connection string pointing to IOST database
            static string connectionString = 
                "Data Source=.;Initial Catalog=IOST;Integrated Security=True";
    
            static void Main(string[] args)
            {
                // Step 1: Insert records into FACULTY table
                InsertFaculty("CSIT",   1, 8, 75000.00m);
                InsertFaculty("BCA",    2, 6, 55000.00m);
                InsertFaculty("CSIT",   3, 8, 80000.00m);
                InsertFaculty("BIT",    4, 8, 60000.00m);
    
                Console.WriteLine("Records inserted successfully.\n");
    
                // Step 2: Retrieve fee of records where Course_Name = 'CSIT'
                RetrieveCSITFee();
    
                Console.ReadLine();
            }
    
            // -------------------------------------------------------
            // Method to INSERT a record into FACULTY table
            // -------------------------------------------------------
            static void InsertFaculty(string courseName, int courseID, 
                                       int noOfSemester, decimal fee)
            {
                // SQL INSERT query using parameterized query to prevent SQL injection
                string insertQuery = @"INSERT INTO FACULTY 
                                       (Course_Name, CourseID, No_of_Semester, fee) 
                                       VALUES 
                                       (@CourseName, @CourseID, @NoOfSemester, @Fee)";
    
                // Using block ensures connection is closed automatically
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(insertQuery, con))
                    {
                        // Add parameters to avoid SQL injection
                        cmd.Parameters.AddWithValue("@CourseName",    courseName);
                        cmd.Parameters.AddWithValue("@CourseID",      courseID);
                        cmd.Parameters.AddWithValue("@NoOfSemester",  noOfSemester);
                        cmd.Parameters.AddWithValue("@Fee",           fee);
    
                        // Open connection
                        con.Open();
    
                        // Execute the INSERT command
                        int rowsAffected = cmd.ExecuteNonQuery();
    
                        Console.WriteLine($"Inserted: {courseName} | Rows Affected: {rowsAffected}");
                    }
                    // Connection is closed automatically at end of using block
                }
            }
    
            // -------------------------------------------------------
            // Method to RETRIEVE fee of FACULTY records where 
            // Course_Name = 'CSIT'
            // -------------------------------------------------------
            static void RetrieveCSITFee()
            {
                // SQL SELECT query with WHERE clause to filter CSIT records
                string selectQuery = @"SELECT Course_Name, CourseID, 
                                              No_of_Semester, fee 
                                       FROM FACULTY 
                                       WHERE Course_Name = @CourseName";
    
                using (SqlConnection con = new SqlConnection(connectionString))
                {
                    using (SqlCommand cmd = new SqlCommand(selectQuery, con))
                    {
                        // Parameterized filter for Course_Name
                        cmd.Parameters.AddWithValue("@CourseName, "CSIT");
    
                        con.Open();
    
                        // Execute the query and read results row by row
                        SqlDataReader reader = cmd.ExecuteReader();
    
                        Console.WriteLine("Fee details for CSIT:");
                        Console.WriteLine("Course_Name | CourseID | No_of_Semester | Fee");
    
                        while (reader.Read())
                        {
                            Console.WriteLine(
                                $"{reader["Course_Name"]} | {reader["CourseID"]} | " +
                                $"{reader["No_of_Semester"]} | {reader["fee"]}"
                            );
                        }
    
                        reader.Close();
                    }
                    // Connection is closed automatically at end of using block
                }
            }
        }
    }
    

    The InsertFaculty method uses a parameterized INSERT with AddWithValue for every field, guarding against SQL injection while adding the four faculty records (two of which are CSIT). The RetrieveCSITFee method then runs a parameterized SELECT ... WHERE Course_Name = @CourseName filtered to "CSIT", opens a SqlDataReader, and loops over reader.Read() to print each matching row's course name, course ID, number of semesters, and fee, giving exactly the fee details for the CSIT records that were inserted.

  4. 45 marksForms and ValidationAnswer

    Write a program to validate the form that takes input user name, password and phone number using JQuery. All fields must be non-empty and phone number must contain exactly 10 digits. [5]

    jQuery Form Validation - Username, Password, and Phone Number

    Complete Solution

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Form Validation using jQuery</title>
    
        <!-- jQuery CDN -->
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
        <style>
            body {
                font-family: Arial, sans-serif;
                margin: 50px;
            }
            .error {
                color: red;
                font-size: 13px;
            }
            .success {
                color: green;
                font-size: 14px;
            }
            input {
                display: block;
                margin: 5px 0 2px 0;
                padding: 6px;
                width: 250px;
            }
            label {
                font-weight: bold;
                margin-top: 10px;
                display: block;
            }
            button {
                margin-top: 15px;
                padding: 8px 20px;
            }
        </style>
    </head>
    <body>
    
    <h2>User Registration Form</h2>
    
    <form id="registrationForm">
    
        <label for="username">Username:</label>
        <input type="text" id="username" placeholder="Enter username" />
        <span class="error" id="usernameError"></span>
    
        <label for="password">Password:</label>
        <input type="password" id="password" placeholder="Enter password" />
        <span class="error" id="passwordError"></span>
    
        <label for="phone">Phone Number:</label>
        <input type="text" id="phone" placeholder="Enter 10-digit phone number" />
        <span class="error" id="phoneError"></span>
    
        <button type="submit">Submit</button>
    
        <p id="successMsg" class="success"></p>
    
    </form>
    
    <script>
        $(document).ready(function () {
    
            // Handle form submission
            $("#registrationForm").submit(function (event) {
    
                // Prevent default form submission
                event.preventDefault();
    
                // Clear previous error messages
                $(".error").text("");
                $("#successMsg").text("");
    
                // Get field values and trim whitespace
                var username = $("#username").val().trim();
                var password = $("#password").val().trim();
                var phone    = $("#phone").val().trim();
    
                var isValid = true;
    
                // Validate Username - must be non-empty
                if (username === "") {
                    $("#usernameError").text("Username is required.");
                    isValid = false;
                }
    
                // Validate Password - must be non-empty
                if (password === "") {
                    $("#passwordError").text("Password is required.");
                    isValid = false;
                }
    
                // Validate Phone - must be non-empty AND exactly 10 digits
                if (phone === "") {
                    $("#phoneError").text("Phone number is required.");
                    isValid = false;
                } else if (!/^\d{10}$/.test(phone)) {
                    $("#phoneError").text("Phone number must contain exactly 10 digits.");
                    isValid = false;
                }
    
                // If all validations pass
                if (isValid) {
                    $("#successMsg").text("Form submitted successfully!");
                }
            });
        });
    </script>
    
    </body>
    </html>
    

    Explanation of Key Parts

    PartPurpose
    $(document).ready()Ensures the DOM is fully loaded before jQuery runs
    event.preventDefault()Stops the form from reloading the page on submit
    .val().trim()Gets the field value and removes leading/trailing spaces
    === ""Checks if the field is empty (non-empty validation)
    /^\d{10}$/.test(phone)Regex to check phone has exactly 10 digits only
    isValid flagTracks overall validation status before showing success

    Validation Rules Applied

    1. Username - must not be empty
    2. Password - must not be empty
    3. Phone Number - must not be empty AND must contain exactly 10 digits (no letters or special characters allowed)
  5. 55 marksApp Servers and Hosting modelsAnswer

    Describe the procedure of deploying .NET core application. [5]

    Deploying a .NET Core Application

    Introduction

    .NET Core is a cross-platform framework, and its Command-Line Interface (CLI) provides tools to build, run, test, and publish .NET Core applications. The .NET Core CLI is installed with the .NET Core SDK and does not need to be installed separately.


    Step-by-Step Deployment Procedure

    Step 1: Verify .NET Core CLI Installation

    Before deploying, confirm that the CLI is properly installed by opening the command prompt and typing:

    dotnet
    

    If it displays usage information, the CLI is installed correctly.


    Step 2: Create the Application

    Create a new project directory and initialize the application using CLI commands:

    mkdir myapp
    cd myapp
    dotnet new console
    

    This creates the necessary project files:

    • Program.cs (main source file)
    • myapp.csproj (project configuration file)

    Step 3: Restore Packages

    Restore all required NuGet packages and dependencies:

    dotnet restore
    

    This ensures all dependencies defined in the .csproj file are downloaded and available.


    Step 4: Build the Application

    Compile the application to check for errors and generate the build output:

    dotnet build
    

    Note: When using .NET Core SDK, the application is built automatically when needed, so there is no need to worry about executing outdated code.


    Step 5: Run the Application (Testing)

    Test the application locally before deployment:

    dotnet run
    

    This compiles (if needed) and executes the application directly.


    Step 6: Publish the Application

    Publish the application to prepare it for deployment on a target server:

    dotnet publish -c Release -o ./publish
    
    • -c Release specifies the Release configuration (optimized build)
    • -o ./publish specifies the output directory where published files are placed

    This generates all necessary files (DLLs, configuration files, runtime files) in the output folder.


    Step 7: Deploy to the Server

    Copy the published output to the target server. For a web application, the deployment typically involves:

    • Placing the published files on the server
    • Configuring a reverse proxy (such as IIS, Nginx, or Apache)
    • The reverse proxy receives requests from the browser and passes them to the ASP.NET Core application, which runs a self-hosted web server (Kestrel)
    Browser --> Reverse Proxy (IIS/Nginx) --> ASP.NET Core App (Kestrel)
    

    Summary Table

    StepCommandPurpose
    Verify CLIdotnetCheck installation
    Create Appdotnet new consoleInitialize project
    Restoredotnet restoreDownload dependencies
    Builddotnet buildCompile source code
    Rundotnet runTest locally
    Publishdotnet publishPrepare for deployment

    Conclusion

    The .NET Core CLI provides a simple and consistent cross-platform procedure for deploying applications. Higher-level IDEs like Visual Studio internally use the same CLI commands to restore, build, and publish .NET Core applications.

  6. 65 marksRendering HTML with ViewsAnswer

    How does ASP.NET core MVC provides patterns-based way to build dynamic website? Explain. [5]

    ASP.NET Core MVC is the Model-View-Controller application model that can be merged with the new ASP.NET Core. It is used to build dynamic websites as it provides fast development. ASP.NET MVC gives a powerful, patterns-based way to build...

  7. 75 marksClient-side strategiesAnswer

    Define state management. Explain the parts of state management on the client side. [5]

    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

    TechniqueStorage LocationSize LimitUse Case
    CookiesBrowserSmallUser preferences, personalization
    Query StringsURLVery smallPage 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.

  8. 85 marksAuthorizationAnswer

    Distinguish between roles and policies. Explain about Kestrel web server in ASP.NET core. [5]

    Roles vs Policies and Kestrel Web Server in ASP.NET Core


    Part 1: Distinguish Between Roles and Policies

    BasisRolesPolicies
    DefinitionRoles are a way to group users based on their job or function (e.g., Admin, User, Manager)Policies are a set of requirements that must be satisfied for authorization to succeed
    ApproachRole-based authorization checks if a user belongs to a specific rolePolicy-based authorization checks one or more requirements against the current user
    FlexibilityLess flexible; limited to simple role membership checksMore flexible; can combine multiple requirements (claims, roles, custom logic)
    DeclarationDeclared using [Authorize(Roles = "Admin")]Declared using [Authorize(Policy = "PolicyName")]
    ConfigurationRoles are assigned directly to usersPolicies are defined in Startup.cs using AddAuthorization()
    ComplexitySuitable for simple access control scenariosSuitable for complex, fine-grained access control scenarios
    ExampleA user is in the "Admin" roleA policy may require a user to be over 18 AND have a verified email

    Part 2: Kestrel Web Server in ASP.NET Core

    Definition

    Kestrel is a cross-platform, lightweight web server for ASP.NET Core. It is the web server that is included by default in ASP.NET Core project templates and is built into the ASP.NET Core framework.


    Key Features of Kestrel

    • Cross-platform: Kestrel runs on Windows, Linux, and macOS, making ASP.NET Core applications truly cross-platform.
    • Default web server: It is automatically included when an ASP.NET Core project is created using the default templates.
    • High performance: Kestrel is designed to be fast and efficient for handling HTTP requests.
    • Self-hosted: It can run independently without requiring an external web server.

    Hosting Models Using Kestrel

    There are two ways Kestrel is used in the Out-of-Process Hosting Model:

    1. Using Kestrel Directly (Edge Server)

    • Kestrel itself acts as an edge server, which directly serves user requests from the internet.
    • No additional web server (like IIS or NGINX) is needed.
    • Suitable for simpler applications or internal services.
    Browser Request --> Kestrel Server --> ASP.NET Core Application
    

    2. Using Kestrel with a Reverse Proxy Server

    • Due to limitations of Kestrel, it cannot be used in all scenarios (e.g., sharing a port, advanced security features).
    • In such cases, powerful servers like IIS, NGINX, or Apache act as a reverse proxy server.
    • The reverse proxy receives the request from the browser and redirects/forwards it to the internal Kestrel server.
    • Kestrel then processes the request and returns the response.
    Browser Request --> Reverse Proxy (IIS/NGINX/Apache) --> Kestrel Server --> ASP.NET Core App
    

    In-Process Hosting (IIS)

    • In this model, the ASP.NET Core app is hosted inside the IIS worker process (w3wp.exe).
    • IIS forwards web requests to the backend ASP.NET Core app running the Kestrel server (out-of-process hosting model).

    Summary

    Kestrel is the heart of ASP.NET Core's web serving capability. It provides a fast, cross-platform, and lightweight server that can either work standalone as an edge server or work behind a powerful reverse proxy like IIS or NGINX for production-grade deployments.

  9. 95 marksDependency Injection and IOC containersAnswer

    Describe the life cycle of Dependency Injection container. [5]

    Life Cycle of Dependency Injection (DI) Container

    In ASP.NET Core, the built-in IoC (Inversion of Control) container manages the creation and lifetime of service instances. The lifetime of a service defines how long an instance lives and when a new instance is created. There are three main service lifetimes:


    1. Transient

    • The IoC container creates a new instance every time the service is requested.
    • Each call to resolve the service produces a fresh object.
    • Best suited for lightweight, stateless services.

    Registration Example:

    services.Add(new ServiceDescriptor(
        typeof(ILog),
        typeof(MyConsoleLogger),
        ServiceLifetime.Transient));
    

    Use case: A simple utility/helper service that holds no shared state.


    2. Scoped

    • The IoC container creates one instance per HTTP request and shares that same instance throughout the entire request.
    • Different requests get different instances.
    • Best suited for services that need to maintain state within a single request (e.g., database context).

    Registration Example:

    services.Add(new ServiceDescriptor(
        typeof(ILog),
        typeof(MyConsoleLogger),
        ServiceLifetime.Scoped));
    

    Use case: A database context or unit-of-work that should be consistent within one request.


    3. Singleton

    • The IoC container creates only one instance for the entire application lifetime.
    • The same instance is reused for every request and every user.
    • Best suited for services that are stateless and expensive to create, or that hold shared application-wide state.

    Registration Example:

    services.Add(new ServiceDescriptor(
        typeof(ILog),
        new MyConsoleLogger())); // single instance passed directly
    

    Use case: A logging service or configuration service shared across the whole application.


    Summary Table

    LifetimeInstance CreatedShared Within
    TransientEvery time requestedNot shared
    ScopedOnce per HTTP requestSingle request
    SingletonOnce per applicationEntire application

    How Registration Works

    Services are registered inside the ConfigureServices() method in Startup.cs:

    public void ConfigureServices(IServiceCollection services)
    {
        // Singleton
        services.Add(new ServiceDescriptor(typeof(ILog), new MyConsoleLogger()));
    
        // Transient
        services.Add(new ServiceDescriptor(typeof(ILog),
            typeof(MyConsoleLogger), ServiceLifetime.Transient));
    
        // Scoped
        services.Add(new ServiceDescriptor(typeof(ILog),
            typeof(MyConsoleLogger), ServiceLifetime.Scoped));
    }
    

    Once registered, the IoC container automatically injects the service via constructor injection wherever the service type is used as a constructor parameter, without the developer needing to manually instantiate it.

  10. 105 marksInheritanceAnswer

    Create a class named EMPLOYEE as super class and ENGINEER and DOCTOR as sub class. Make your own assumptions as properties and methods. [5]

    This question demonstrates inheritance in C, where a base (super) class EMPLOYEE is created, and derived (sub) classes ENGINEER and DOCTOR inherit its properties and methods. The derived classes extend the base class with their own speci...

  11. 115 marksObject-Relational MapperAnswer

    What is the task of ORM? Discuss about open redirect attacks. [5]

    --- ORM (Object-Relational Mapper) is a programming technique that maps objects in an application to tables in a relational database. Its primary tasks include: - Data Mapping: Maps class properties to database table columns, so develope...

  12. 1210 marksapplying polymorphism in code extensibilitAnswer

    Write short notes on: a. Polymorphism b. Hidden Field [5+5]

    Short Notes


    a. Polymorphism (5 Marks)

    Definition

    The word polymorphism means "having many forms." It is the ability of a function, method, or object to behave differently in different contexts. In C#, polymorphism can be static (compile-time) or dynamic (run-time).


    1. Static Polymorphism (Compile-Time Polymorphism)

    The mechanism of linking a function with an object during compile time is called static binding. C# implements static polymorphism through function overloading.

    In function overloading, multiple methods share the same name but differ in the number or type of parameters.

    Example:

    using System;
    namespace PolymorphismApplication {
        class Printdata {
            void print(int g) {
                Console.WriteLine(g);
            }
            void print(double f) {
                Console.WriteLine(f);
            }
            void print(string s) {
                Console.WriteLine(s);
            }
        }
    }
    

    Here, the method print() is overloaded to handle int, double, and string data types. The compiler decides which version to call at compile time.


    2. Dynamic Polymorphism (Run-Time Polymorphism)

    C# allows the creation of abstract classes that provide partial class implementation. The implementation is completed when a derived class inherits from the abstract class and overrides its methods. The correct method is resolved at run time.

    Key Points:

    • Uses abstract keyword for the base class and methods.
    • Derived classes use override keyword to provide specific implementations.
    • Enables method overriding.

    Example:

    abstract class Shape {
        public abstract void Draw();
    }
    class Circle : Shape {
        public override void Draw() {
            Console.WriteLine("Drawing Circle");
        }
    }
    class Rectangle : Shape {
        public override void Draw() {
            Console.WriteLine("Drawing Rectangle");
        }
    }
    

    Importance of Polymorphism

    • Promotes code extensibility and reusability.
    • Allows a single interface to represent different underlying forms (data types or classes).
    • Makes programs easier to maintain and scale.

    b. Hidden Field (5 Marks)

    Definition

    A hidden field is an HTML form element that allows data to be stored on the client side without being displayed on the page. When the user performs an action (such as form submission), the hidden field value is passed back to the server side along with the form data.


    Purpose

    Sometimes we require certain data (such as a user ID or session-related value) to be available across requests without showing it to the user. Hidden fields serve this purpose by embedding the data in the HTML form invisibly.


    How Hidden Fields Work in ASP.NET Core MVC

    Step 1: GET Method - Set the hidden field value

    The GET version of the action method creates an object and passes it to the view:

    [HttpGet]
    public IActionResult SetHiddenFieldValue() {
        User newUser = new User() {
            Id = 101,
            Name = "John",
            Age = 31
        };
        return View(newUser);
    }
    

    Step 2: View - Render the hidden field

    In the view, the Id field is rendered as a hidden input so it is not visible to the user but is included in the form:

    @model User
    <form method="post">
        <input type="hidden" name="Id" value="@Model.Id" />
        <input type="text" name="Name" value="@Model.Name" />
        <button type="submit">Submit</button>
    </form>
    

    Step 3: POST Method - Read the hidden field value

    The POST version reads the hidden field value from IFormCollection:

    [HttpPost]
    public IActionResult SetHiddenFieldValue(IFormCollection keyValues) {
        var id = keyValues["Id"];   // Retrieves the hidden field value
        return View();
    }
    

    Key Points

    AspectDetail
    VisibilityNot visible to the user on the page
    TransmissionSent to the server on form submission
    Use CaseStoring IDs, tokens, or state data across requests
    SecurityShould not be used for sensitive data as it can be viewed in page source

    Summary

    Hidden fields are a simple and effective way to persist data between HTTP requests in a stateless web environment without exposing it in the UI. In ASP.NET Core MVC, they are commonly used with IFormCollection or model binding to retrieve the stored values on the server side.