w3resource

HtmlHelper - Hidden field


In this tutorial, we will learn how to generate hidden input field using HtmlHelper in razor view of an MVC application.

Just like other HtmlHelpers we have previously discussed, HtmlHelper class includes two extension methods to generate a hidden input field () element in a view. These methods includes:

  • Hidden()
  • HiddenFor()

Using the following Activities model we will illustrate the use of the Hidden() and HiddenFor() method.

//Demo: Activity Model
public class Activity
{
    public int Id {get; set;}
    public string ActivityName {get; set;}
    public string Description {get; set;}
    public string Status {get; set;}
}

Hidden()

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

Hidden() method signature

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

Like every other methods Hidden() method has many overloads as possible.

The following example creates a hidden field for Id property of Activity model. It binds Id with the hidden field, so that it can assign value of Id to the hidden field and visa-versa.

//Demo: Html.Hidden() in Razor View
@model ActivityTab.Models.Activity
@Html.Hidden("Id")
Html Result:
<input id="Id" 
            name="Id" 
            type="hidden" 
            value="1" />

HiddenFor

The HiddenFor helper method is a strongly typed extension method. It generates a hidden input element for the model property specified using a lambda expression. HiddenFor method binds the specified model object property to <input type="hidden">. Hence, it automatically sets a value of the model property to hidden field.

HiddenFor() method signature

MvcHtmlString Html.HiddenFor(Expression<Func<dynamic,TProperty>> expression)

The HiddenFor() method is also and can be method loaded like every other methods.

Example: HiddenFor() in Razor View
@model ActivityTab.Models.Activity

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

In the demo above, the first parameter in HiddenFor() method is a lambda expression that specifies the model property to be bound to the hidden field. In the above example, we specified Id property. So, that an input text element with id and name set to property name will be generated. The value attribute will be set to the value of Id property which is 2 in the above example.

The data- attribute of html5 seen in the above input field. These attributes are used for the validation in ASP.Net MVC.



Inviting useful, relevant, well-written and unique guest posts