Hidden HTML Helper in ASP.NET Core MVC

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 developers 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 is used to identify the input field in the server-side script processing the form data. The value attribute contains the data that will be sent to the server when the form is submitted. Hidden fields are often used for various purposes, such as:

  • Passing Data: This is storing data that is needed for processing on the server side but shouldn’t be modified by the user.
  • Maintaining State: Tracking certain states or identifiers, especially in multi-step forms or when working with sessions.
  • Security: Storing tokens or unique identifiers to prevent cross-site request forgery (CSRF) attacks.
  • Client-Side Calculations: Storing intermediate values for client-side calculations that must be returned to the server.

Note: While hidden input fields are not directly visible or editable by the user through the interface, they can still be viewed and potentially modified by users who inspect the page’s HTML source code or use developer tools. Therefore, sensitive information should not be stored in hidden input fields or 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.

What is the Hidden HTML Helper Method in ASP.NET Core MVC?

The Hidden HTML helper method in ASP.NET Core MVC generates a hidden input field in an HTML form. You can manually specify the field’s name and value. This method is useful when you need to include data in the form submission that is not directly related to model properties or when you want to specify the field’s name and value explicitly.

Syntax: @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.

Example to Understand Hidden HTML Helper in ASP.NET Core MVC

In this demo, 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 into it.

namespace HTML_HELPER.Models
{
    public class Student
    {
        public int Id { get; set; }
        public string? Name { get; set; }
        public string? Branch { get; set; }
    }
}

Next, modify the Home Controller as follows:

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;
namespace HTML_HELPER.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Student student = new Student() { Id = 1, Name = "Pranaya", Branch = "CSE" };
            return View(student);
        }

        [HttpPost]
        public string Index(Student student)
        {
            return $"Id: {student.Id}, Name: {student.Name}, Branch: {student.Branch}";
        }
    }
}
Modify the Index.cshtml file as follows:

The following example creates a hidden field ID with the Id property of the Student model. It binds the ID to the hidden field so that it can assign the ID value to it.

@model HTML_HELPER.Models.Student

<div>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.Hidden("Id", Model.Id)

        <label for="Name">Name</label>
        @Html.TextBox("Name", Model.Name, new { @class = "form-control", placeholder = "Enter your Name" })

        <label for="Branch">Branch</label>
        @Html.TextBox("Branch", Model.Branch, new { @class = "form-control", placeholder = "Enter your Branch" })
        <input type="submit" value="Submit" />
    }
</div>

Understanding the code:

  • Html.BeginForm: This creates the form element with the specified action and controller names and the form submission method (in this case, POST).
  • @Html.Hidden: This 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.

Now, run the application, and you will see the following output. Please note that it shows the name and branch but not the student’s ID value.

Hidden HTML Helper Method in ASP.NET Core MVC

Now, if you inspect the HTML element, you will see that it is generating 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.

HiddenFor() HTML Helper Method in ASP.NET Core MVC

Using the Hidden HTML Helper, you can ensure that the hidden input fields are generated correctly with the necessary attributes and values. This approach also promotes cleaner and more maintainable code.

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.

What is the HiddenFor() HTML Helper Method in ASP.NET Core MVC?

The HiddenFor helper method in ASP.NET Core MVC, on the other hand, 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 is strongly typed. which means it is tied to a model property. It 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

<div>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        @Html.HiddenFor(m => m.Id)

        <label for="Name">Name</label>
        @Html.TextBoxFor(m => m.Name, new { @class = "form-control", placeholder = "Enter your Name" })

        <label for="Branch">Branch</label>
        @Html.TextBoxFor(m => m.Branch, new { @class = "form-control", placeholder = "Enter your Branch" })
        <input type="submit" value="Submit" />
    }
</div>

In this example:

  • Html.BeginForm: This creates the form element as before.
  • Html.HiddenFor(m => m.Id): This 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. When the form is submitted, the ID value will be included in the POST data.

Run the application, and you will get the same output as the previous example.

What are the Differences Between Hidden and HiddenFor Helper Methods in ASP.NET Core MVC?

In ASP.NET Core MVC, both Hidden and HiddenFor generate hidden input fields. Understanding the differences between them is important for effective data handling and manipulation in MVC applications. 

Hidden Helper Method in ASP.NET Core MVC
  • Usage: The @Html.Hidden helper generates a hidden input field that is not visible to the user but can be used to store and post data back to the server. It’s useful for storing data that you want to pass back to the server without displaying it or allowing modification by the user.
  • Syntax: You can use @Html.Hidden by specifying the name of the data you want to store and, optionally, the value. For example, @Html.Hidden(“UserId”, “123”) would generate a hidden input field for storing a user ID value of “123”.
  • Flexibility: This method allows for a more flexible naming convention since you can explicitly specify the input field’s name. This can be useful in situations where the name of the field doesn’t directly correspond to a property on your model.
HiddenFor Helper Method in ASP.NET Core MVC
  • Usage: The @Html.HiddenFor helper is strongly typed and generates a hidden input field for a specific model property. This ensures that the field name and value are directly tied to model properties, which helps with model binding upon form submission.
  • Syntax: You use @Html.HiddenFor with a lambda expression that specifies the model property. For example, @Html.HiddenFor(model => model.UserId) would generate a hidden input field that is bound to the UserId property of your model.
  • Strongly Typed: Since @Html.HiddenFor is strongly typed to your model properties, it provides compile-time checking of the property names. This reduces the risk of errors due to typos or property name changes not being reflected in your views.

In the next article, I will discuss How to Create a Custom HTML Helper in the ASP.NET Core MVC Application with Examples. I explain Hidden Field HTML Helper in the ASP.NET Core MVC Application with Examples in this article. I hope this article will help you with your needs.

Leave a Reply

Your email address will not be published. Required fields are marked *