Sunday, April 29, 2018

How will you create your own custom html helper method.

We can create custom HTML helpers in two ways,
Using static methods
Using extension methods

using static method


public static class CustomHelper
{
        public static MvcHtmlString Image(string source,string altTxt,string width,string height){
            //TagBuilder creates a new tag with the tag name specified
            var ImageTag = new TagBuilder("img");
            //MergeAttribute Adds attribute to the tag
            ImageTag.MergeAttribute("src", source);
            ImageTag.MergeAttribute("alt", altTxt);
            ImageTag.MergeAttribute("width", width);
            ImageTag.MergeAttribute("height", height);
            //Return an HTML encoded string with SelfClosing TagRenderMode
            return MvcHtmlString.Create(ImageTag.ToString(TagRenderMode.SelfClosing));
        }
}

Using Extension Methods


public static MvcHtmlString Image(this HtmlHelper htmlhelper, string source, string altTxt, string width, string height)
{
            var ImageTag = new TagBuilder("img");
            ImageTag.MergeAttribute("src", source);
            ImageTag.MergeAttribute("alt", altTxt);
            ImageTag.MergeAttribute("width", width);
            ImageTag.MergeAttribute("height", height);
}

No comments:

Followers

Link