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)
- {
-
- var builder = new TagBuilder("img");
-
-
- builder.MergeAttribute("id", id);
-
- builder.MergeAttribute("src", src);
-
- builder.MergeAttribute("alt", alt);
-
- builder.MergeAttribute("height", height);
-
- builder.MergeAttribute("width", width);
-
-
-
- return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));
- }
- }
- }
Note
MvcHtmlString class inherits HtmlString and HtmlString class implements IHtmlString interface.
Notice the below code snippet for TextBox HTML helper. If we want to display image in MVC we do not have any HTML helper for an image which we can use like TextBox HTML helper. In the below snippet if we try to use Image helper we do not have an option for image.
If we want to display images in MVC, then we have to use img control as below in the View.
- <img src="@Url.Content(ImagePath)" alt="@Model.AlternateText" />
Now, here I will use custom image HTML helper which we have created as above. If we want to use a custom helper in all views then we need to add the below highlighter line in web.config file under <system.web> section.
After adding this line we will get our custom Image helper or you can import @using CustomeHtmlHelper.CustomeImageHelper on the top of your View. Now, you will be able to see our custom image HTML helper as below
Here is final image helper with all parameters which we can pass to image extension method, you can use this HTML helper like another helper.
I hope it helps you.
If you have any questions on this please feel free to ask me by posting comments down below.
Thank you for reading.