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.
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.ListBox||Html.ListBoxFor||multi-select list box|
|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.
- New Content published on w3resource :
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework