Home / ASP.NET - MVC / HtmlHelper - Hidden fields

HtmlHelper - Hidden field

The HtmlHelper class has two extension methods to create Textbox( with the given name specifies, values, and html attributes.Html.HiddenFor creates an input text element with the specified model attribute using a lambda expression.

Example Hidden() and HiddenFor ():

public class Student
{
    public int StudentId { get; set; set; }
    [Display(Name="Name")]
    public string StudentName { get; set; set; }
    public int Age { get; set; set; }
    public bool isNewlyEnrolled { get; set; set; }
    public string Password { get; set; set; }
}

Hidden()

The Html.Hidden() method creates a hidden element with name, value and html attributes.

Hidden() method syntax

MvcHtmlString Html.Hidden(string name, object value, object htmlAttributes)

Hidden has many methods. Please visit MSDN for all Hidden.

The following example creates a hidden field for the StudentId property in the Student class. So that it can assign the value of StudentId to the hidden field and vice versa.

@model Student

@Html.Hidden("StudentId")

HTML result:


HiddenFor

HiddenFor creates a element with the specified attribute using a lambda expression.

HiddenFor method syntax

MvcHtmlString Html.HiddenFor(Expression> expression)

See more methods of HiddenFor.

Example:

@model Student

@Html.HiddenFor(m => m.StudentId)

HTML result:

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


Did you find this article helpful?

Support the author so they can write more quality articles!

Tư vấn lộ trình CNTT 🤖