Search code examples
asp.netasp.net-mvchtml-helper

How to create Image Action Link Html helper in Asp.Net MVC?


How can i create action image html helper in asp.net mvc like below..

@Html.ActionImage("actionName", "controllerName", "routeValues")

similarly like below helper...

@Html.Action("actionName", "controllerName", "routeValues")

Thanks in advance.....


Solution

  • You can create custom helper class like..

     namespace MyNamespace 
     {  
        public static class MyHeleprs
        { 
            public static MvcHtmlString ActionImage(this HtmlHelper html, string actionName, string controllerName, object routeValues, string imagePath, string alt)
             {
                 var url = new UrlHelper(html.ViewContext.RequestContext);
    
                // build the <img> tag
                var imgBuilder = new TagBuilder("img");
                imgBuilder.MergeAttribute("src", url.Content(imagePath));
                imgBuilder.MergeAttribute("alt", alt);
                string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
    
                // build the <a> tag
                var anchorBuilder = new TagBuilder("a");
    
                anchorBuilder.MergeAttribute("href", url.Action(action, controllerName, routeValues));
                anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
                string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
    
                return MvcHtmlString.Create(anchorHtml);
             } 
        } 
    }
    

    To make this helper available in your view, add its namespace as follows:

    @using MyNamespace
    

    Now you can get html helper in your views like below...

    @Html.ActionImage(actionName, controllerName, routeValues, imagePath, imgAlt)