HTML Helpers
Here, you will learn what HTML helpers are and how to use them in the razor view.
The HtmlHelper
class renders HTML controls in the razor view. It binds the model object to HTML controls to display the value of model properties into those controls and also assigns the value of the controls to the model properties while submitting a web form. So always use the HtmlHelper
class in razor view instead of writing HTML tags manually.
The following figure shows the use of the HtmlHelper
class in the razor view.
In the above figure, @Html is an object of the HtmlHelper
class. (@ symbol is used to access server-side object in razor syntax). Html is a property of the HtmlHelper
class included in base class of razor view WebViewPage
. The ActionLink()
and DisplayNameFor()
are extension methods included in the HtmlHelper
class.
The HtmlHelper
class generates HTML elements. For example, @Html.ActionLink("Create New", "Create")
would generate anchor tag <a href="/Student/Create">Create New</a>
.
There are many extension methods for HtmlHelper class, which creates different HTML controls.
The following table lists the HtmlHelper
methods and HTML control each method renders.
Extension Method | Strongly Typed Method | Html Control |
---|---|---|
Html.ActionLink() | NA | <a></a> |
Html.TextBox() | Html.TextBoxFor() | <input type="textbox"> |
Html.TextArea() | Html.TextAreaFor() | <input type="textarea"> |
Html.CheckBox() | Html.CheckBoxFor() | <input type="checkbox"> |
Html.RadioButton() | Html.RadioButtonFor() | <input type="radio"> |
Html.DropDownList() | Html.DropDownListFor() | <select> <option> </select> |
Html.ListBox() | Html.ListBoxFor() | multi-select list box: <select> |
Html.Hidden() | Html.HiddenFor() | <input type="hidden"> |
Html.Password() | Html.PasswordFor() | <input type="password"> |
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. |
The difference between calling the HtmlHelper
methods and using an HTML tags is that the HtmlHelper
method is designed to make it easy to bind to view data or model data.
Learn about various HtmlHelper
methods in the next few sections.