In this blog, I am going to explain about Custom Image HTML Helper which can be created using extension method according to the project's need and it can be used like other normal HTML helpers.
To demonstrate Custom Image HTML Helper, I have created a static class and static method. Custom Image Helper method returns MvcHtmlString and it will take a few parameters which will be used for creating new tag builders like src, alt, height, width and htmlhelper class which is used with this keyword so we can add extension method on that class.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- namespace CustomeHtmlHelper
- {
- public static class CustomeImageHelper
- {
- public static MvcHtmlString Image(this HtmlHelper helper, string id, string src, string alt, string height, string width)
- {
- // Below line is used for generate new tag with img
- var builder = new TagBuilder("img");
- // Below five lines are used for adding atrribute for img tag
- builder.MergeAttribute("id", id);
- builder.MergeAttribute("src", src);
- builder.MergeAttribute("alt", alt);
- builder.MergeAttribute("height", height);
- builder.MergeAttribute("width", width);
- // this method will return MVChtmlstring and Create method will render as selfclosing tag.
- return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
- }
- }
- }


Viknaraj ManogararajahPosted Jul 19, 2018, 6:46 AM
Nice Article...........
Dipak ZalaPosted Jun 26, 2018, 2:02 AM
Nice Article...