ASP.NET MVC provides many built-in HTML Helpers. With help of HTML Helpers we can reduce the amount of typing of HTML tags for creating a HTML page.
For example we use Html.TextBox() helper method it generates html input textbox. Write the following code snippet in MVC View:
<%=Html.TextBox("txtName",20) %>
above code snippet generates following html:
<input id="txtName" name="txtName" type="text" value="20" />
List of built-in HTML Helpers provided by ASP.NET MVC:
- ActionLink() – Links to an action method.
- BeginForm() – Marks the start of a form and links to the action method that renders the form.
- CheckBox() – Renders a check box.
- DropDownList() – Renders a drop-down list.
- Hidden() – Embeds information in the form that is not rendered for the user to see.
- ListBox() – Renders a list box.
- Password() – Renders a text box for entering a password.
- RadioButton() – Renders a radio button.TextArea() – Renders a text area (multi-line text box).
- TextBox () – Renders a text box.
How to develop our own Custom HTML Helpers?
For developing custom HTML helpers the simplest way is to write an extension method for the HtmlHelper class. See the below code, it builds a custom Image HTML Helper for generating image tag.
using System; using System.Web.Mvc; namespace MvcHelpers { public class CustomHtmlHelpers { public static TagBuilder Image(this HtmlHelper helper, string imageUrl, string alt) { if(!string.IsNullOrEmpty(imageUrl)) { var imageTag = new TagBuilder("img"); imageTag.MergeAttribute("src", imageUrl); imageTag.MergeAttribute("alt", alt); return imageTag; } return null; } } }
- TagBuilder represents a class that is used by HTML helpers to build HTML elements.
- TagBuilder.MergeAttribute(String, String) method adds an attribute to the tag by using the specified key/value pair.
The next step is to make HTML helper available to views, to do that we should include the name space of custom HTML helper class into Web.config.
<pages> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> <add namespace="MvcHelpers" /> </namespaces> </pages>
Build the solution to make sure the helper method is available to views. Go to any view in the solution access the newly created HTML image helper method.
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %> <!DOCTYPE html> <html> <head runat="server"> <title>Home</title> </head> <body> <div> <h2> <%= Html.Encode(ViewData["Message"]) %> </h2> <%= Html.Image("/Images/logo.png","logo") %> </div> </body> </html>
<%= Html.Image("/Images/logo.png","logo") %>
Above image HTML helper generates the following HTML:
<img src="/Images/logo.png" alt="logo" />
Image Tag Helper is simple example of HTML helpers, we can put any sort of complex logic into HTML Helpers & access them with in the views with a simple method call. in turn which makes the view simpler.