Custom Html Helper in MVC


Custom HTML Helper

In my previous article I have discussed about the html helper class. html helper class doesn’t support all html tags. So if we want to add tags which behave like html helper then we need to create our own custom html helper class.
For this example I am going to create custom html helper class for image tag. We need to add extension method for image tag. Extension method will always be static. In this method we need to pass the class name in which we need to add this extension method and for html helper it is HtmlHelper. So we need to pass this class reference as parameter to this extension method.
Add mvc project and add a class in your project and make it static. Now create static method which returns IHtmlString.
  
 using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace WebApplication2
{
    public static class custom_htmlhelper
    {
        
        public static IHtmlString image(this HtmlHelper hclass, string source)
        {
            TagBuilder tb = new TagBuilder("img");
            tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(source));
            return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));

        }
        public static IHtmlString image(this HtmlHelper hclass, string source,string alt)
        {
            TagBuilder tb = new TagBuilder("img");
            
            tb.Attributes.Add("src", VirtualPathUtility.ToAbsolute(source));
            tb.Attributes.Add("alt", alt);
            return new MvcHtmlString(tb.ToString(TagRenderMode.SelfClosing));

        }
    }
}

  
I have created two image method using method overloading. Now go to view and add image tag.

No comments:

Post a Comment