Back to: ASP.NET Core Tutorials For Beginners and Professionals
Hidden Field HTML Helper in the ASP.NET Core MVC
In this article, I will discuss Hidden Field HTML Helper in ASP.NET Core MVC Application with Examples. Please read our previous article discussing Password Field HTML Helper in ASP.NET Core MVC Application.
What is Hidden Field in HTML
A hidden input field in a web application is an HTML <input> element that is not visible to the user. It stores data that can be sent with a form to the server upon submission. Although the user cannot see or interact with a hidden input field, it can hold values we want to pass to the server without needing user interaction or display. The basic syntax for a hidden input field looks like this: <input type=”hidden” name=”hiddenFieldName” value=”someValue”>
Here, type=”hidden” specifies that the input field is hidden from the user. The name attribute identifies the input field, and the value attribute contains the data sent to the server when the form is submitted.
Note: While hidden input fields are not directly visible or editable by the user through the interface, they can still be viewed and modified by users who inspect the page’s HTML source code or use browser developer tools. Therefore, sensitive information should not be stored in hidden input fields and should be properly encrypted or handled securely to prevent security vulnerabilities.
How Do We Create Hidden Filed Using HTML Helper in ASP.NET Core MVC?
To create a Hidden Field, i.e., <input type=”Hidden”> using HTML Helpers in ASP.NET Core MVC, we must use Hidden or HiddenFor methods within our Razor views. The Hidden method is used when you manually specify the form field’s name, while HiddenFor is used with model properties, providing a strongly typed approach. That means the Hidden() HTML Helper method is loosely typed, whereas the HiddenFor() HTML Helper method is strongly typed.
Example to Understand Hidden HTML Helper Method in ASP.NET Core MVC:
In ASP.NET Core MVC, the Hidden HTML helper generates a hidden form field. This method is useful when we need to include data in the form submission that is not directly related to model properties or when we want to specify the field’s name and value explicitly. The syntax is @Html.Hidden(“fieldName,“ “value”). Here, “fieldName” is the name of the hidden field, and “value” is the value assigned to it. When the form is submitted, the value of this hidden field is sent to the server along with the other form data.
When you load a form to edit a record, such as a product or user, we need to pass the record’s identifier (like the Id field) back to the server when the form is submitted. The user doesn’t need to see or edit the ID, so it’s stored in a hidden field. Let us understand this with an example. Here, we will use the following Student model to understand the Hidden() and HiddenFor() HTML Helper methods. First, create a class file named Student.cs within the Models folder and copy and paste the following code.
namespace HTML_HELPER.Models { public class Student { public int Id { get; set; } public string? Name { get; set; } public string? Branch { get; set; } } }
Creating Student Controller:
Next, create an Empty MVC Controller named StudentController within the Controllers folder and copy and paste the following code. Here, we have created the Controller with two action methods. The Get version will display the Edit View, which the user can use to edit the information, and when the form is submitted, the Post action method will handle the data.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class StudentController : Controller { public ActionResult Edit() { Student student = new Student() { Id = 1, Name = "Pranaya", Branch = "CSE" }; return View(student); } [HttpPost] public string Edit(Student student) { //Process the Request return $"Id: {student.Id}, Name: {student.Name}, Branch: {student.Branch}"; } } }
Creating the Edit View
Next, create the Edit view and copy and paste the following code. Here, we create a hidden field ID with the ID property of the Student model. The hidden field will store the user’s ID; when the form is submitted, this ID value is also submitted to the server.
@model HTML_HELPER.Models.Student @{ ViewData["Title"] = "Edit"; } <form asp-action="Edit" asp-controller="Student" method="post" class="form-horizontal"> @Html.Hidden("Id", Model.Id) <div class="form-group mt-1"> <label for="Name" class="control-label col-md-2">Name</label> <div class="col-md-10"> @Html.TextBox("Name", Model.Name, new { @class = "form-control", placeholder = "Enter your Name" }) </div> </div> <div class="form-group mt-1"> <label for="Branch" class="control-label col-md-2">Branch</label> <div class="col-md-10"> @Html.TextBox("Branch", Model.Branch, new { @class = "form-control", placeholder = "Enter your Branch" }) </div> </div> <div class="form-group mt-1"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Submit" class="btn btn-primary" /> </div> </div> </form>
Here, @Html.Hidden generates a hidden input field. The first parameter (“Id”) is the input element’s name, which will be used to identify the data on the server. The second parameter (Model.Id) is the value you want to send along with the form. Run the application, navigate to the Student/Edit URL, and see the following output. Please note that it shows the name and branch but not the student’s ID value.
If you inspect the HTML element, you will see it generates the following HTML element for the hidden field.
<input data-val=”true” data-val-required=”The Id field is required.” id=”Id” name=”Id” type=”hidden” value=”1” />
Now, when you click on the Submit button, you will see, along with the Name and Brach, it is also sending the ID value to the server, and you will get the following output.
Note: Please note that hidden fields can still be manipulated by users with some technical knowledge, so sensitive or critical information should always be validated and processed securely on the server side.
Example to Understand HiddenFor() HTML Helper Method in ASP.NET Core MVC:
The HiddenFor helper method in ASP.NET Core MVC is strongly typed and is used with model properties. It generates a hidden input field for a specific property of the model bound to the view. This approach ensures type safety and enables direct mapping between the form field and the model property, reducing the errors due to mistyped field names.
The HiddenFor() method takes a lambda expression as an argument, which specifies the property of the model that the hidden input element represents. Let us understand this with an example. Please modify the Index.cshtml file as follows:
@model HTML_HELPER.Models.Student @{ ViewData["Title"] = "Edit"; } <form asp-action="Edit" asp-controller="Student" method="post" class="form-horizontal"> @Html.HiddenFor(m => m.Id) <div class="form-group mt-1"> <label for="Name" class="control-label col-md-2">Name</label> <div class="col-md-10"> @Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder = "Enter your Name" }) </div> </div> <div class="form-group mt-1"> <label for="Branch" class="control-label col-md-2">Branch</label> <div class="col-md-10"> @Html.TextBoxFor(m => m.Branch, new { @class = "form-control", placeholder = "Enter your Branch" }) </div> </div> <div class="form-group mt-1"> <div class="col-md-offset-2 col-md-10"> <input type="submit" value="Submit" class="btn btn-primary" /> </div> </div> </form>
Here, Html.HiddenFor(m => m.Id) generates a hidden input field based on the model’s Id property. The lambda expression m => m.ID specifies the property for which you want to create the hidden field. The ID value will be included in the POST data when the form is submitted. Run the application, and you will get the same output as the previous example.
Multi-Step Forms Real-time Example using Hidden HTML Helper Method in ASP.NET Core MVC:
We will use hidden fields to carry data from one step to another in a multi-step form. Information collected in previous steps must be preserved for subsequent steps without being visible to the user. We will use a simple use case of a User Registration Process where we collect user details in multiple steps.
In step 1, collect the user’s personal details (e.g., Name and Email). So, we will create the following to collect the user’s personal information.
In step 2, collect address details (e.g., Street, City, and Zip Code). Once the user clicks the Next button in Step 1, we will navigate him to the following page, where he will enter the address.
In Step 3, we will Review the details and submit the registration. That means once the user clicks on the Next button in Step 2, we will navigate the user to the following page, where he will verify the details and click on the submit button.
Once the user clicks on the Submit button, the data should saved in the database, and the user should receive a successful registration message as shown in the below image:
Let us proceed and implement this example step by step:
Step 1: Setting Up the Model
We will start by creating a model to represent the user registration details. So, create a class file named RegistrationViewModel.cs within the Models folder and copy and paste the following code.
using System.ComponentModel.DataAnnotations; namespace HTML_HELPER.Models { public class PersonalInfoViewModel { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } } public class AddressInfoViewModel : PersonalInfoViewModel { public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } } public class RegistrationSummaryViewModel { public string FirstName { get; set; } public string LastName { get; set; } public string Email { get; set; } public string Street { get; set; } public string City { get; set; } public string ZipCode { get; set; } } }
Step 2: Create the Controller
We will manage the flow between the steps in the controller. So, create an Empty MVC Controller named RegistrationController within the Controllers folder and copy and paste the following code.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class RegistrationController : Controller { // Handles GET requests for the 'PersonalInfo' action, displaying the Personal Info form [HttpGet] public IActionResult PersonalInfo() { // Simply returns the 'PersonalInfo' view return View(); } // Handles POST requests when the 'PersonalInfo' form is submitted [HttpPost] public IActionResult PersonalInfo(PersonalInfoViewModel model) { // Checks if the model passed from the form is valid based on DataAnnotations if (ModelState.IsValid) { // If the data is valid, redirect to the 'AddressInfo' action, passing the personal info as route data return RedirectToAction("AddressInfo", new { model.FirstName, model.LastName, model.Email }); } // If the model is invalid, re-render the 'PersonalInfo' view with the existing model (to show validation errors) return View(model); } // Handles GET requests for the 'AddressInfo' action, displaying the Address Info form [HttpGet] public IActionResult AddressInfo(string firstName, string lastName, string email) { // Creates a new AddressInfoViewModel and populates it with the personal info passed from the previous step var model = new AddressInfoViewModel { FirstName = firstName, // Personal info carried from the previous step LastName = lastName, Email = email }; // Passes the populated model to the 'AddressInfo' view return View(model); } // Handles POST requests when the 'AddressInfo' form is submitted [HttpPost] public IActionResult AddressInfo(AddressInfoViewModel model) { // Checks if the model passed from the form is valid based on DataAnnotations if (ModelState.IsValid) { // If the data is valid, redirect to the 'RegistrationSummary' action, passing both personal and address info as route data return RedirectToAction("RegistrationSummary", new { model.FirstName, model.LastName, model.Email, model.Street, model.City, model.ZipCode }); } // If the model is invalid, re-render the 'AddressInfo' view with the existing model (to show validation errors) return View(model); } // Handles GET requests for the 'RegistrationSummary' action, displaying a summary of all the registration details [HttpGet] public IActionResult RegistrationSummary(string firstName, string lastName, string email, string street, string city, string zipCode) { // Creates a new RegistrationSummaryViewModel and populates it with the personal and address info passed from the previous step var model = new RegistrationSummaryViewModel { FirstName = firstName, // Personal info LastName = lastName, Email = email, Street = street, // Address info City = city, ZipCode = zipCode }; // Passes the populated model to the 'RegistrationSummary' view return View(model); } // Handles POST requests when the 'RegistrationSummary' form is submitted [HttpPost] public IActionResult Submit(RegistrationSummaryViewModel model) { // Here you would typically save the registration data to a database // Redirects to the 'Success' action once the data is saved return RedirectToAction("Success"); } // Handles GET requests for the 'Success' action, displaying a success message after registration is complete public IActionResult Success() { // Returns the 'Success' view return View(); } } }
The above example implements a multi-step form submission process to persist data across multiple HTTP requests. Each registration process step has its own view and handles validation to ensure data is correctly passed between steps. The final step involves saving the data and showing a success message.
Creating the Views
Let us implement all the views.
Step 1 View: PersonalInfo.cshtml
This is the view where the user enters their personal details. So, create a view named PersonalInfo.cshtml and copy and paste the following code.
@model PersonalInfoViewModel @{ ViewData["Title"] = "Step1"; } <h2>Step 1: Personal Details</h2> <form asp-action="PersonalInfo" asp-controller="Registration" method="post" class="mt-4"> <!-- Bootstrap form-group for First Name --> <div class="form-group mb-3"> @Html.LabelFor(m => m.FirstName, new { @class = "form-label" }) @Html.TextBoxFor(m => m.FirstName, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.FirstName, "", new { @class = "text-danger" }) </div> <!-- Bootstrap form-group for Last Name --> <div class="form-group mb-3"> @Html.LabelFor(m => m.LastName, new { @class = "form-label" }) @Html.TextBoxFor(m => m.LastName, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.LastName, "", new { @class = "text-danger" }) </div> <!-- Bootstrap form-group for Email --> <div class="form-group mb-3"> @Html.LabelFor(m => m.Email, new { @class = "form-label" }) @Html.TextBoxFor(m => m.Email, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Email, "", new { @class = "text-danger" }) </div> <!-- Bootstrap submit button with styling --> <button type="submit" class="btn btn-primary">Next</button> </form>
Step 2 View: AddressInfo.cshtml
This view collects the user’s address details and includes hidden fields to retain the data from Step 1. So, create a view named AddressInfo.cshtml and copy and paste the following code.
@model AddressInfoViewModel @{ ViewData["Title"] = "Step2"; } <h2>Step 2: Address Details</h2> <form asp-action="AddressInfo" asp-controller="Registration" method="post" class="mt-4"> <!-- Hidden fields to preserve Step 1 data --> @Html.HiddenFor(m => m.FirstName) @Html.HiddenFor(m => m.LastName) @Html.HiddenFor(m => m.Email) <!-- Bootstrap form-group for Street --> <div class="form-group mb-3"> @Html.LabelFor(m => m.Street, new { @class = "form-label" }) @Html.TextBoxFor(m => m.Street, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.Street, "", new { @class = "text-danger" }) </div> <!-- Bootstrap form-group for City --> <div class="form-group mb-3"> @Html.LabelFor(m => m.City, new { @class = "form-label" }) @Html.TextBoxFor(m => m.City, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.City, "", new { @class = "text-danger" }) </div> <!-- Bootstrap form-group for Zip Code --> <div class="form-group mb-3"> @Html.LabelFor(m => m.ZipCode, new { @class = "form-label" }) @Html.TextBoxFor(m => m.ZipCode, new { @class = "form-control" }) @Html.ValidationMessageFor(m => m.ZipCode, "", new { @class = "text-danger" }) </div> <!-- Bootstrap submit button --> <button type="submit" class="btn btn-primary">Next</button> </form>
Step 3 View: RegistrationSummary.cshtml
This step reviews the data and allows the user to submit the registration, with hidden fields carrying the data from previous steps. So, create a view named RegistrationSummary.cshtml and copy and paste the following code.
@model RegistrationSummaryViewModel @{ ViewData["Title"] = "Step3"; } <div class="container"> <h2 class="mb-4 text-center">Step 3: Review Your Details</h2> <form asp-action="Submit" asp-controller="Registration" method="post" class="mt-4"> <!-- Hidden fields to preserve all data --> @Html.HiddenFor(m => m.FirstName) @Html.HiddenFor(m => m.LastName) @Html.HiddenFor(m => m.Email) @Html.HiddenFor(m => m.Street) @Html.HiddenFor(m => m.City) @Html.HiddenFor(m => m.ZipCode) <!-- Bootstrap-styled review of the details --> <div class="card shadow-sm mb-4"> <div class="card-body"> <h4 class="card-title mb-4 text-primary">Your Details</h4> <div class="row mb-3"> <div class="col-sm-3 fw-bold">First Name:</div> <div class="col-sm-9">@Model.FirstName</div> </div> <div class="row mb-3"> <div class="col-sm-3 fw-bold">Last Name:</div> <div class="col-sm-9">@Model.LastName</div> </div> <div class="row mb-3"> <div class="col-sm-3 fw-bold">Email:</div> <div class="col-sm-9">@Model.Email</div> </div> <div class="row mb-3"> <div class="col-sm-3 fw-bold">Street:</div> <div class="col-sm-9">@Model.Street</div> </div> <div class="row mb-3"> <div class="col-sm-3 fw-bold">City:</div> <div class="col-sm-9">@Model.City</div> </div> <div class="row mb-3"> <div class="col-sm-3 fw-bold">Zip Code:</div> <div class="col-sm-9">@Model.ZipCode</div> </div> </div> </div> <!-- Bootstrap submit button --> <div class="text-center"> <button type="submit" class="btn btn-success btn-lg">Submit</button> </div> </form> </div>
Success View: Success.cshtml
After submitting the form, the user is directed to the success page. So, create a view named Success.cshtml within the Views/Shared folder and then copy and paste the following code.
@{ ViewData["Title"] = "Success"; } <div class="text-center mt-5"> <h2 class="display-4 text-success">Registration Successful!</h2> <p class="lead mt-4">Thank you for registering.</p> </div>
Now, run the application and test the functionalities, and it should work as expected.
In the next article, I will discuss how to create a custom HTML helper in the ASP.NET Core MVC application with examples and explain the hidden field of HTML helper in this article. I hope this article will help you with your needs.
Registration Open For New Online Training
Enhance Your Professional Journey with Our Upcoming Live Session. For complete information on Registration, Course Details, Syllabus, and to get the Zoom Credentials to attend the free live Demo Sessions, please click on the below links.