HTML Helpers in ASP.NET MVC

An HTML Helper is just a method that returns a HTML string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input>, <button> and <img> tags etc.

You can also create your own HTML Helpers to render more complex content such as a menu strip or an HTML table for displaying database data.

Different types of HTML Helpers

There are three types of HTML helpers as given below:

  1. 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.

    1. @helper ListingItems(string[] items)
    2. {
    3. <ol>
    4. @foreach (string item in items)
    5. {
    6. <li>@item</li>
    7. }
    8. </ol>
    9. }
    10.  
    11. <h3>Programming Languages:</h3>
    12.  
    13. @ListingItems(new string[] { “C”, “C++”, “C#” })
    14.  
    15. <h3>Book List:</h3>
    16.  
    17. @ListingItems(new string[] { “How to C”, “how to C++”, “how to C#” })
  2. 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-

    1. Standard Html Helpers

      These helpers are used to render the most common types of HTML elements like as HTML text boxes, checkboxes etc. A list of most common standard html helpers is given below:

      HTML Element
      Example
      TextBox
      @Html.TextBox(“Textbox1”, “val”)
      Output: <input id=”Textbox1″ name=”Textbox1″ type=”text” value=”val” />
      TextArea
      @Html.TextArea(“Textarea1”, “val”, 5, 15, null)
      Output: <textarea cols=”15″ id=”Textarea1″ name=”Textarea1″ rows=”5″>val</textarea>
      Password
      @Html.Password(“Password1”, “val”)
      Output: <input id=”Password1″ name=”Password1″ type=”password” value=”val” />
      Hidden Field
      @Html.Hidden(“Hidden1”, “val”)
      Output: <input id=”Hidden1″ name=”Hidden1″ type=”hidden” value=”val” />
      CheckBox
      @Html.CheckBox(“Checkbox1”, false)
      Output: <input id=”Checkbox1″ name=”Checkbox1″ type=”checkbox” value=”true” /> <input name=”myCheckbox” type=”hidden” value=”false” />
      RadioButton
      @Html.RadioButton(“Radiobutton1”, “val”, true)
      Output: <input checked=”checked” id=”Radiobutton1″ name=”Radiobutton1″ type=”radio” value=”val” />
      Drop-down list
      @Html.DropDownList (“DropDownList1”, new SelectList(new [] {“Male”, “Female”}))
      Output: <select id=”DropDownList1″ name=”DropDownList1″> <option>M</option> <option>F</option> </select>
      Multiple-select
      Html.ListBox(“ListBox1”, new MultiSelectList(new [] {“Cricket”, “Chess”}))
      Output: <select id=”ListBox1″ multiple=”multiple” name=”ListBox1″> <option>Cricket</option> <option>Chess</option> </select>
    2. Strongly Typed HTML Helpers

      These helpers are used to render the most common types of HTML elements in strongly typed view like as HTML text boxes, checkboxes etc. The HTML elements are created based on model properties.

      The strongly typed HTML helpers work on lambda expression. The model object is passed as a value to lambda expression, and you can select the field or property from model object to be used to set the id, name and value attributes of the HTML helper. A list of most common strongly-typed html helpers is given below:

      HTML Element
      Example
      TextBox
      @Html.TextBoxFor(m=>m.Name)
      Output: <input id=”Name” name=”Name” type=”text” value=”Name-val” />
      TextArea
      @Html.TextArea(m=>m.Address , 5, 15, new{}))
      Output: <textarea cols=”15″ id=”Address” name=” Address ” rows=”5″>Addressvalue</textarea>
      Password
      @Html.PasswordFor(m=>m.Password)
      Output: <input id=”Password” name=”Password” type=”password”/>
      Hidden Field
      @Html.HiddenFor(m=>m.UserId)
      Output: <input id=” UserId” name=” UserId” type=”hidden” value=”UserId-val” />
      CheckBox
      @Html.CheckBoxFor(m=>m.IsApproved)
      Output: <input id=”Checkbox1″ name=”Checkbox1″ type=”checkbox” value=”true” /> <input name=”myCheckbox” type=”hidden” value=”false” />
      RadioButton
      @Html.RadioButtonFor(m=>m.IsApproved, “val”)
      Output: <input checked=”checked” id=”Radiobutton1″ name=”Radiobutton1″ type=”radio” value=”val” />
      Drop-down list
      @Html.DropDownListFor(m => m.Gender, new SelectList(new [] {“Male”, “Female”}))
      Output: <select id=”Gender” name=”Gender”> <option>Male</option> <option>Female</option> </select>
      Multiple-select
      Html.ListBoxFor(m => m.Hobbies, new MultiSelectList(new [] {“Cricket”, “Chess”}))
      Output: <select id=”Hobbies” multiple=”multiple” name=”Hobbies”> <option>Cricket</option> <option>Chess</option> </select>
    3. Templated HTML Helpers

      These helpers figure out what HTML elements are required to render based on properties of your model class. This is a very flexible approach for displaying data to the user, although it requires some initial care and attention to set up. To setup proper HTML element with Templated HTML Helper, make use of DataType attribute of DataAnnitation class.

      For example, when you use DataType as Password, A templated helper automatically render Password type HTML input element.

      Templated Helper
      Example
      Display
      Renders a read-only view of the specified model property and selects an appropriate HTML element based on property’s data type and metadata.
      Html.Display(“Name”)
      DisplayFor
      Strongly typed version of the previous helper
      Html.DisplayFor(m => m. Name)
      Editor
      Renders an editor for the specified model property and selects an appropriate HTML element based on property’s data type and metadata.
      Html.Editor(“Name”)
      EditorFor
      Strongly typed version of the previous helper
      Html.EditorFor(m => m. Name)
  3. Custom Html Helpers

    The easiest way to create a new HTML Helper is to create a static method that returns a string. Imagine, for example, that you decide to create a new HTML Helper that renders an HTML <label> tag. You can use the class in Listing 2 to render a<label> .

    Listing 2 – Helpers\LabelHelper.cs

    usingSystem;namespaceMvcApplication1.Helpers{
              publicclassLabelHelper
    
              {
                   publicstaticstringLabel(string target,string text)
                   {
                        returnString.Format("<label for='{0}'>{1}</label>", target, text);
                   }
              }}

    There is nothing special about the class in Listing 2. The Label() method simply returns a string.

    The modified Index view in Listing 3 uses the LabelHelper to render HTML <label> tags. Notice that the view includes an<%@ imports %> directive that imports the Application1.Helpers namespace.

    Listing 2 – Views\Home\Index2.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index2.aspx.cs" Inherits="MvcApplication1.Views.Home.Index2"%>
    <%@ Import Namespace="MvcApplication1.Helpers" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headid="Head1"runat="server">
    
         <title>Index2</title></head><body>
         <div>
              <%using(Html.BeginForm())
              { %>
                   <%=LabelHelper.Label("firstName","First Name:") %>
                   <br/>
    
                   <%=Html.TextBox("firstName")%>
                   <br/><br/>
                   <%=LabelHelper.Label("lastName","Last Name:") %>
                   <br/>
                   <%=Html.TextBox("lastName")%>
                   <br/><br/>
                   <inputtype="submit"value="Register"/>
              <%} %>
    
         </div></body></html>

    Creating HTML Helpers with Extension Methods

    If you want to create HTML Helpers that work just like the standard HTML Helpers included in the ASP.NET MVC framework then you need to create extension methods. Extension methods enable you to add new methods to an existing class. When creating an HTML Helper method, you add new methods to the HtmlHelper class represented by a view’s Html property.

    The class in Listing 3 adds an extension method to the HtmlHelper class named Label(). There are a couple of things that you should notice about this class. First, notice that the class is a static class. You must define an extension method with a static class.

    Second, notice that the first parameter of the Label() method is preceded by the keyword this. The first parameter of an extension method indicates the class that the extension method extends.

    Listing 3 – Helpers\LabelExtensions.cs

    usingSystem;usingSystem.Web.Mvc;namespaceMvcApplication1.Helpers{
         publicstaticclassLabelExtensions
         {
              publicstaticstringLabel(thisHtmlHelper helper,string target,string text)
              {
                   returnString.Format("<label for='{0}'>{1}</label>", target, text);
    
              }
         }}

    After you create an extension method, and build your application successfully, the extension method appears in Visual Studio Intellisense like all of the other methods of a class (see Figure 2). The only difference is that extension methods appear with a special symbol next to them (an icon of a downward arrow).

    Using the Html.Label() extension method

    Figure 02: Using the Html.Label() extension method (Click to view full-size image)

    The modified Index view in Listing 4 uses the Html.Label() extension method to render all of its <label> tags.

    Listing 4 – Views\Home\Index3.aspx

    <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index3.aspx.cs" Inherits="MvcApplication1.Views.Home.Index3" %>
    
    <%@ Import Namespace="MvcApplication1.Helpers" %>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><htmlxmlns="http://www.w3.org/1999/xhtml"><headid="Head1"runat="server">
         <title>Index3</title></head><body>
         <div>
    
              <%using(Html.BeginForm())
              { %>
                   <%=Html.Label("firstName","First Name:") %>    
                   <br/>
                   <%=Html.TextBox("firstName")%>
                   <br/><br/>
                   <%=Html.Label("lastName","Last Name:") %>    
                   <br/>
                   <%=Html.TextBox("lastName")%>
    
                   <br/><br/>
                   <inputtype="submit"value="Register"/>
              <%} %>
         </div></body></html>

Advertisements
By Sriramjithendra Posted in ASP.NET

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s