Saturday 29 July 2017

HTML Helpers

In this section, you will learn what are Html helpers and how to use them in the razor view.
HtmlHelper class generates html elements using the model class object in razor view. It binds the model object to html elements to display value of model properties into html elements and also assigns the value of the html elements to the model properties while submitting web form. So always use HtmlHelper class in razor view instead of writing html tags manually.
The following figure shows the use of HtmlHelper class in the razor view.
html helpers
HTML Helpers
As you can see in the above figure, @Html is an object of HtmlHelper class . (@ 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. ActionLink() and DisplayNameFor() is extension methods included in HtmlHelper class.
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 HtmlHelper methods and html control each method generates.
HtmlHelperStrogly Typed HtmlHelpersHtml Control
Html.ActionLinkAnchor link
Html.TextBoxHtml.TextBoxForTextbox
Html.TextAreaHtml.TextAreaForTextArea
Html.CheckBoxHtml.CheckBoxForCheckbox
Html.RadioButtonHtml.RadioButtonForRadio button
Html.DropDownListHtml.DropDownListForDropdown, combobox
Html.ListBoxHtml.ListBoxFormulti-select list box
Html.HiddenHtml.HiddenForHidden field
PasswordHtml.PasswordForPassword textbox
Html.DisplayHtml.DisplayForHtml text
Html.LabelHtml.LabelForLabel
Html.EditorHtml.EditorForGenerates 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.

Points to Remember :

  1. HtmlHelper extension method generates html elements based on model properties.
  2. It is advisable to use "For" extension methods for compile time type checking e.g. TextBoxFor, EditorFor, CheckBoxFor etc.

No comments:

Post a Comment

Recent Post

Parallel Task in .Net 4.0