Creating Custom HTML Helpers
1. Create a static method in a static class
2. The first parameter has to be the type to which we are adding the extension method
3. Return type should be IHtmlString, as these strings are excluded from html encoding
4. To help, creating of HTML tags, use TagBuilder class
5. Include the namespace of the helper method in either the view or web.config
Add a folder as "CustomHtmlHelpers"
Add a class below as a CustomHtmlHelpers.cs
using System.Web.Mvc; // for HtmlHelper
namespace MVCDemo.CustomHtmlHelpers
{
public static class CustomHtmlHelpers //should be static
{
public static IHtmlString Image(this HtmlHelper helper, string src, string alt)
{
TagBuilder tb = new TagBuilder("img");
tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(src));
tb.Attributes.Add("alt", alt);
return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));
}
}
}
@Html.Image(@Model.Photo, @Model.AlternateText) //After building, can use Image Html helper
to avoid adding namespace each page, you could add the name at web.config
<add namespace="MVCDemo.CustomHtmlHelpers"/>