Skip to main content

How To Create Custom HTML Helper in ASP.NET MVC? Here Is The Way.

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.

What are HTML Helpers in MVC?


  • An HTML helper is a method that is used to render the specified html content in View. It can be implemented as an extension method.
  • If you know the ASP.NET webforms, you might know the concept of web controls. e.g. <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>
  • HTML helpers methods are the same as web controls it allows to render appropriate HTML in view.

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 in this tutorial, we will create our own custom helper for <img src="" /> tag


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.

How to Create an Extension Method for HtmlHelper Class?


  • We have to create a static method in static class.
  • First parameter has to be the type to which we are adding the extension method. In our case, it is HtmlHelper Class.
  • Return type should be IHtmlString, as these strings are excluded from html encoding.
  • To create HTML tag, we have to use TagBuilder class
  • Include the namespace of the helper method in view or web.config

Here 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>

Conclusion


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.

Comments

Popular posts from this blog

दान धर्माची बदललेली परिभाषा

नमस्कार! बरेच वेळा मनात विचार येतात पण लिहिण्याचा प्रयत्न पहिल्यांदाच करत आहे. तरी चूक भूल माफी असावी. आजकाल Whatsapp आणि Facebook यांच्यामुळे जग जवळ आले आहे, पण सगळ्याच गोष्टी share करण्याचा जणु छंदच लोकांना जडला आहे. अर्थात थोड्याफार प्रमाणात मी पण share करत असतो पण अगदी थोडक्या प्रमाणात. आता कोणी दानधर्म करत असेल तर तो पण यावर सर्रास Share केला जातो, मुळात दान याची वाख्याच लोक विसरत चालले आहे. याचीसुद्धा मार्केटिंग होऊ लागली आहे. मुळात दान हे निस्वार्थ भावनेने केले पाहिजे (असे दान ज्याला परताव्याची इच्छा नसते), जेव्हा लोक आपण दान करतो असा दाखवायचा प्रयत्न करतात मग ते facebook share असो किवां whatsapp status,post किवां इतर कोणतेही माध्यम याचा अर्थ असा कि दान करताना या लोकांनी मला प्रसिद्धी मिळेल किवां मी किती दानशुर आहे हे दाखवण्याची भावना मनात ठेवून केलेले दान होय. अशी परताव्याची भावना मनात ठेवून केलेले दान हे दान नसून व्यवहाराच नाही का? व्यवहारात जस आपण पैसे देऊन त्या बदल्यात वस्तू,सेवा खरेदी करतो, तसेच परताव्याचा विचार करून केलेले दान म्हणजे व्यवहाराच. असो माझे विचार

Why Interface For Decoupled System? A Note On How To Design Decoupled System in ASP.NET MVC

An Interface At first, interfaces came into focus because there was no multiple inheritance supported by C#, meaning you could not inherit from multiple classes, but you could implement multiple interfaces. The interfaces are grouping of object in terms of behavior. An interface contains only signatures. There is no implementation, only the signatures of the functionality the interface provides. An interface can contain signatures of methods, properties, indexers & events. Interface doesn't do anything like classes and abstract classes, it just defines what the class will perform if some class inherits it. An interface can also be inherited from another interface. If we take an example of USB (Universal Serial Bus), it's an interface which has signature of Connection functionality. The USB interface only knows I have to connect with Desktop Computer or laptop or anything, but it does not know what implementation will come to connection. It may be Pen d

A cookie wrapper class. Easily read, create, update and delete cookies in MVC

Create a new class with name CookieHelper.cs In your project and paste the following code. public class CookieHelper { #region Constants /// <summary> /// The cookie name /// </summary> public const string cookieName = "UserName"; #endregion #region Enums public enum EnumCookieInterval { SECOND = 0, MINUTE = 1, DAY = 2, MONTH = 3, YEAR = 4 }; #endregion #region Utilities /// <summary> /// Calculates the cookie lifetime. /// </summary> /// <param name="duration">The duration.</param> /// <param name="durationType">Type of the duration.Use enum to specify</param> /// <returns>Expire date for cookie</returns> private static DateTime CalculateCookieLifetime(int duration, Enum