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.


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.


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.MergeAttribute("name", nameAttribute);

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

            // Add Additional Attributes

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


@{Layout = null; }

    ViewBag.Title = "Home Page";

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

@*Full HTML Extension*@
            "Suzy wearing cone",
            "img-responsive img-rounded",
            new { width = "50px", height = "50px", data_action = "slide" })

<br />

@*Overloaded HTML Extension*@
            "Suzy wearing cone")



Error | ASP.NET Developer


Error message

  • Warning: Cannot modify header information - headers already sent by (output started at /srv/disk9/1218369/www/ in drupal_send_headers() (line 1232 of /srv/disk9/1218369/www/
  • PDOException: SQLSTATE[42000]: Syntax error or access violation: 1142 INSERT command denied to user '1218369_b2cf'@'' for table 'watchdog': INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4, :db_insert_placeholder_5, :db_insert_placeholder_6, :db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => cron [:db_insert_placeholder_2] => Attempting to re-run cron while it is already running. [:db_insert_placeholder_3] => a:0:{} [:db_insert_placeholder_4] => 4 [:db_insert_placeholder_5] => [:db_insert_placeholder_6] => [:db_insert_placeholder_7] => [:db_insert_placeholder_8] => [:db_insert_placeholder_9] => 1534727871 ) in dblog_watchdog() (line 160 of /srv/disk9/1218369/www/
The website encountered an unexpected error. Please try again later.