How To Create Custom HTML Helper In ASP.NET MVC 4.

  • Introduction
    This article explains how to Create Custom HTML Helper in ASP.NET MVC 4.
  • HTML HELPERS  :
    HTML helpers used for render html. Html helper is same as asp.net web form controls.Html helpers are extremely lightweight. html helpers dos not have event model as well as dose not use view state.
    The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a complete list):
    Html.ActionLink()
    Html.BeginForm()
    Html.CheckBox()
    Html.DropDownList()
    Html.EndForm()
    Html.Hidden()
    Html.ListBox()
    Html.Password()
    Html.RadioButton()
    Html.TextArea()
    Html.TextBox()

You can create your own html helper and use in your project. In this article we are creating one custom html helper for image control in Asp.Net MVC 4.
Add one class in your project named “CustomHtmlHelper” and add one static method named “Image” with four parameters.
the return type of the method is “IHtmlString“. refer below code snippet.

public static class CustomHtmlHelper
{
public static IHtmlString Image(this HtmlHelper html, string src, string alt, object htmlAttributes)
{
TagBuilder tb = new TagBuilder(“img”);
tb.Attributes.Add(“src”, src);
tb.Attributes.Add(“alt”, alt);
tb.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}

After create one new view and import reference of the “CustomHtmlHelper” class then you can access the image custom html helper in your view. Refer below code snippet.

@{
Layout = null;
}
@using MVCTest.Models.CustomHtmlHelper;
<!DOCTYPE html>
<html>
<head>
<meta name=”viewport” content=”width=device-width” />
<title>TestView</title>
</head>
<body style=”margin-left:50px;”>
<div>
<h3>Custom Html Helper : </h3>
</div>
<div>
@Html.CustomImage(Url.Content(@”/Images/EMP_20166201836.jpg”), “EmpPhoto”, new { @height = “100px;”, @width = “100px” })
</div>
</body>
</html>

After completion of all steps build solution then run and navigate the URL, You will see the output. It will create <img> tag and set set the properties as per passed html attribute parameter and other parameters.

  • Output : 

CustomHelper

  • HTML Source :

CustomHelper2