There are three types of HTML helpers as given below:
- Inline Html Helpers – These are create in the same view by using the Razor @helper tag. These helpers can be reused only on the same view.
@helper ListingItems(string[] items) { <ol> @foreach (string item in items) { <li>@item</li> } </ol> } <h3>Programming Languages:</h3> @ListingItems(new string[] { "C", "C++", "C#" }) <h3>Book List:</h3> @ListingItems(new string[] { "How to C", "how to C++", "how to C#" })
- Built-In Html Helpers – Built-In Html Helpers are extension methods on the HtmlHelper class. The Built-In Html helpers can be divided into three categories-
- Custom Html Helpers – You can also create your own custom helper methods by creating an extension method on the HtmlHelper class or by creating static methods with in a utility class.
public static class CustomHelpers { //Submit Button Helper public static MvcHtmlString SubmitButton(this HtmlHelper helper, string buttonText) { string str = "<input type=\"submit\" value=\"" + buttonText + "\" />"; return new MvcHtmlString(str); } //Readonly Strongly-Typed TextBox Helper public static MvcHtmlString TextBoxFor < TModel, TValue > (this HtmlHelper < TModel > htmlHelper, Expression < Func < TModel, TValue >> expression, bool isReadonly) { MvcHtmlString html = default (MvcHtmlString); if (isReadonly) { html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression, new {@ class = "readOnly", @readonly = "read-only" }); } else { html = System.Web.Mvc.Html.InputExtensions.TextBoxFor(htmlHelper, expression); } return html; } }