Create a Hidden Field in ASP.NET MVC

Learn how to generate hidden field using the HtmlHelper in razor view in this section.

The HtmlHelper class includes two extension methods to generate a hidden field <input type="hidden"> element in a razor view: HiddenFor() and Hidden().

We will use the following Student model class throughout this article.

Example: Student Model
public class Student
{
    public int StudentId { get; set; }
    public string StudentName { get; set; }
}

Html.HiddenFor()

The Html.HiddenFor<TModel, TProperty> extension method is a strongly typed extension method generates a hidden input element for the model property specified using a lambda expression.

Visit docs.microsoft.com to know all the overloads of HiddenFor() method.

Example: HiddenFor() in Razor View
@model Student

@Html.HiddenFor(m => m.StudentId)
Html Result:
<input data-val="true" 
            data-val-number="The field StudentId must be a number." 
            data-val-required="The StudentId field is required." 
            id="StudentId" 
            name="StudentId" 
            type="hidden" 
            value="" />

In the above example, the first parameter in HiddenFor() method is a lambda expression that specifies the model property to be bind with the hidden field. We have specified the StudentId property in the above example. So, it generates an input text element with id & name set to the property name. The value attribute will be set to the value of the StudentId property.

Please notice that it has created data- HTML5 attribute, which is used for the validation in ASP.NET MVC.

ADVERTISEMENT

Html.Hidden()

The Html.Hidden() method generates a input hidden field element with specified name, value and html attributes.

Visit MSDN to know all the overloads of Hidden() method.

Example: Html.Hidden() in Razor View
@model Student

@Html.Hidden("StudentId")
Html Result:
<input id="StudentId" 
            name="StudentId" 
            type="hidden" 
            value="1" />
Want to check how much you know ASP.NET MVC?