Mayur Lohite Published a new article on Web, Mobile & Software Dev, Web Development, Web & Mobile Design
14-Sep-2019
In this article, I will explain how to create a custom HTML helper as per your requirement.
If you know the MVC and Helpers already, you can skip the next paragraph and if you don't know, here is an explanation about helpers.
<asp:TextBox /><asp:label />
If you use these controls in web form on browsers, they will converted to their equivalent HTML controls like TextBox
will be <input type="text" />
and label
will be <span></span>
Let's take an example of how HTML helper looks like:
@Html.TextBox("Myname","Mayur Lohite")
This HTML helper will render the following HTML in view.
<input type="text" name="Myname" id="Myname" value="Mayur Lohite" />
The MVC provides a rich set of HTML helpers, e.g. @html.TextBox()
, @Html.TextArea()
, @Html.CheckBox()
, etc. but if you take a closer look in HTML Helpers, there is no helper present for Image
tag i.e. <img src="" />
So we have to achieve something like:
@Html.MyImage("~/Image/mayur.jpg","Mayur Lohite" />
So, it will generate the following HTML.
<img src="/Image/mayur.jpg" alt="Mayur Lohite" />
If you take a closer look at @Html
in view, it is a property of HtmlHelper
class. Right click on @Html
in view and click on Go to Definition. You will get the following output.
Now to create custom HTML helper, we need to create extension method of HtmlHelper
class. So we can access our custom method by @Html
property.
static
method in static
class.HtmlHelper
Class.IHtmlString
, as these string
s are excluded from html encoding.TagBuilder
classHere is the code:
namespace MyMVCApp.CustomHtmlHelpers { public static class CustomHtmlHelpers { public static IHtmlString MyImageHelper(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)); } } }
So we have created our Extension method. Now it's time to call it in our view. The following code will give you an idea of how we can call it on view.
Here is the view:
@using MyMVCApp.CustomHtmlHelpers; <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Custom Helper</title> </head> <body> <div> @Html.MyImage("~/Images/mayur.jpg", "Mayur Lohite") </div> </body> </html>
The MVC provides us the flexibility to create our own HTML helpers by using an extension method of HtmlHelper
class. We can develop the custom HTML helper as per the requirement, e.g., for image, some widgets, etc.