HTML Helpers

General information

HTML Helpers are methods in ASP.NET MVC that are used to generate HTML elements in a View. They are used to create and render HTML controls (such as textboxes, dropdownlists, checkboxes, etc.) in a strongly-typed and efficient way. They provide a way to create reusable and consistent HTML code, reducing the amount of repetitive and error-prone markup that needs to be written. HTML Helpers take model properties as input and generate the appropriate HTML, which means that HTML Helpers also play a role in model binding and validation.

Examples

Example 1: Text Box

The following code will generate a text input field with the value of the "Name" property of the Model:

@Html.TextBoxFor(mdl => mdl.Name)

Example 2: Text Area

The following code will generate a text area tied to the "Description" property of the Model:

@Html.TextAreaFor(mdl => mdl.Description)

Example 3: Check Box

The following code will generate a check box for the boolean property "IsOn" of the Model:

@Html.CheckBoxFor(mdl => mdl.IsOn)

Example 4: Dropdown List

The following code will generate a dropdown list taking the items from the list "PersonList" of the Model:

@Html.DropDownListFor(mdl => mdl.Person, @Converter.ToMvcList(Model.PersonList))

It is necessary to convert the List in the Model to a form that can be put in a dropdown list, which is why the second argument was included in this HTML Helper function.

Example 5: Hidden

The following code will generate an invisible element storing the value of the ID Property of the Model:

@Html.HiddenFor(mdl => mdl.ID)

Attributes

HTML Helpers can also have attributes like HTML Tags, such as "id", "class", "style" and "readonly". They are specified the following way:

@Html.TextBoxFor(mdl => mdl.Name, new { @id = "someId", @class = "someClass", @style = "width:90%", @readonly = readonly })

Last updated