w3resource

HTML Helpers


In the previous tutorials, we learnt about Razor as a templating engine and its syntax. In this section, we will learn about Html helpers, how to use them with the razor syntax.

HtmlHelpers are helper classes that generates html elements in the view using the model class objects. It binds the model object to html elements to display model values or properties into html elements and then assigns the value of the html elements to the model properties when web forms are submitted.

ASP.NET MVC encourages us to use html helpers as often as possible, instead of writing raw html tags.

The figure below illustrates the use of HtmlHelper class alongside with razor syntax in an ASP.NET View.

asp.net html helpers

As illustrated in the code snippet above, @Html is an object of HtmlHelper class. (The @ symbol is used to access server-side object in razor syntax).

Html is a property of type HtmlHelper included in base class of razor view WebViewPage.

LabelFor() and ValidationMessageFor() is extension methods included in HtmlHelper class.

HtmlHelper class generates html elements after compilation. For instance, @Html.ActionLink("Create New", "Create") would generate anchor tag <a href="/Activity/Create">Create New</a>.

There are other extension methods for HtmlHelper classes, which is used to create different html controls.

The following table lists HtmlHelper methods and html control each method generates.

HtmlHelper Strongly Typed HtmlHelpers Html Control
Html.ActionLink Anchor link
Html.TextBox Html.TextBoxFor Textbox
Html.TextArea Html.TextAreaFor TextArea
Html.CheckBox Html.CheckBoxFor Checkbox
Html.RadioButton Html.RadioButtonFor Radio button
Html.DropDownList Html.DropDownListFor Dropdown, combobox
Html.ListBox Html.ListBoxFor multi-select list box
Html.Hidden Html.HiddenFor Hidden field
Password Html.PasswordFor Password textbox
Html.Display Html.DisplayFor Html text
Html.Label Html.LabelFor Label
Html.Editor Html.EditorFor Generates Html controls based on data type of specified model property e.g. textbox for string property, numeric field for int, double or other numeric type.

One may ask, what is the need of HTML helpers, since on compilation they still become html tags. The answer to this is that HTML helpers enables us to bind models to our views very easily.

In the next couple of tutorials, we will look at each of theses HTML helpers, and explain them in detail.



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