HTML Helpers

Web page by Kevin Harris of Homer IL

Please contact Kevin Harris of Homer IL concerning this web site

HTML Helpers

"Some HTML Helpers use the meta data specified in the model attributes to build the appropriate HTML elements."

HTML Helpers are extension methods on the HTMLHelper class which are used to render HTML content in Razor views. HTML Helpers are an optional aid to developers. In MVC HTML helpers perform a similar function to the server controls in Web Forms. However unlike server controls, HTML helpers do not use view state or contain an event model. Some Html helpers, such as HTML.Editor, use the meta data specified in the model attributes to build the appropriate HTML elements. Custom HTML helpers can easily be created as extension methods.

HTML helpers are html factories which return an HTML-encoded string of type MvcHTMLString. Many HTML helpers have different versions which can be used depending on whether the data is weakly or strongly typed. For example if the data is passed through the ViewData dictionary (weakly typed) then the "Html.Display" helper could be used.

@Html.Display("FirstName")


If the data is passed to the view in a model (strongly typed), then the "Html.DisplayFor" helper could be used.

@Html.DisplayFor(model => model.FirstName)


If the data is passed to the view in a model (strongly typed), and you wish to display every field in the model, then the "Html.DisplayForModel" helper could be used.

@Html.DisplayFor()


Note: Using strongly typed data for the HTML helpers has the benefit of Intellisense and compile-time error checking, which will not be available with weakly typed data.

Some of the standard HTML helpers in MVC are:

  • Html.ActionLink
  • Html.BeginForm
  • Html.CheckBox
  • Html.Display
  • Html.DropDownList
  • Html.Editor
  • Html.Hidden
  • Html.ListBox
  • Html.Password
  • Html.RadioButton
  • Html.TextArea
  • Html.TextBox
  • Html.ValidationMessage
  • Html.ValidationSummary


Creating Custom HTML Helpers

The standard MVC HTML helpers include some simple elements which are commonly used in web applications. Custom HTML helpers can be used to create HTML helpers which are not provided by MVC, such as buttons, images, grid views, and more complex types of controls. The standard helpers also have some limitations which can be overcome by writing custom HTML helpers. For example the incorrect use of anonymous types for styling, or adding HTML5 attributes, can cause run-time errors. The anonymous types can be added as parameters to a custom help to enforce strict typing to provide compile-time syntax checking.

TagBuilder is a class designed to create HTML Tags. TagBuilder automatically adds open/closing elements, attributes, and multiple CSS classes in the correct format. The tag builder also provides for passing in attributes as anonymous types with the help of the HtmlHelper.AnonymousObjectToHtmlAttributes method.


Custom Image HTML Helper

.Custom Image HTML Helper


Custom Image HTML Helper

The following code creates a custom HTML helper for creating an img tag.

using System.Web.Mvc;

// Put in project namespace
namespace HTMLHelpers
{
    public static class HtmlExtensionImage
    {
        // Overloaded HTML Helper Extension without Class and Name Attribute
        // Always include include parameter for anonymous object dictionary
        public static MvcHtmlString Image(this HtmlHelper htmlHelper,
            string srcText,
            string altText,
            object htmlAttributes = null)
        {
            return HtmlExtensionImage.Image(htmlHelper, srcText, altText,
                                            string.Empty, string.Empty, htmlAttributes);
        }

        // Full HTML Helper Extension
        public static MvcHtmlString Image(this HtmlHelper htmlHelper,
            string srcText,
            string altText,
            string cssClass,
            string nameAttribute,
            object htmlAttributes = null)
        {
            // Pass in name of tag you wish to build
            TagBuilder tb = new TagBuilder("img");

            // Add Name and ID elements
            if (!string.IsNullOrWhiteSpace(nameAttribute))
            {
                nameAttribute = TagBuilder.CreateSanitizedId(nameAttribute);
                tb.GenerateId(nameAttribute);
                tb.MergeAttribute("name", nameAttribute);
            }

            // Add src and alt elements
            tb.MergeAttribute("src", srcText);
            tb.MergeAttribute("alt", altText);  
            
            // Add classes
            if (!string.IsNullOrWhiteSpace(cssClass))
            {
                tb.AddCssClass(cssClass);
            }

            // Add Additional Attributes
            tb.MergeAttributes(HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));

            return MvcHtmlString.Create(tb.ToString(TagRenderMode.SelfClosing));
        }
    }
}


HtmlExtensionImage.cs


@{Layout = null; }
@Styles.Render("~/Content/css")
@Scripts.Render("~/bundles/modernizr")

@{
    ViewBag.Title = "Home Page";
}

@*<img src="~/Images/suzycone.png" alt="Suzy wearing cone"/>*@

@*Full HTML Extension*@
@Html.Image("/Images/suzycone.png",
            "Suzy wearing cone",
            "img-responsive img-rounded",
            "imgSuzy",
            new { width = "50px", height = "50px", data_action = "slide" })

<br />

@*Overloaded HTML Extension*@
@Html.Image("/Images/suzycone.png",
            "Suzy wearing cone")


@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/bootstrap")


Index.cshtml