Blog - Single Post

ActionLink with image - ASP.NET MVC Extension methods

  • Tuesday, January 6, 2015
  • by hbopuri

public static class ExtendedHelpers
    {
        public static MvcHtmlString ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName, string controllerName,
            string imgClass, string anchorClass, string imgAlt = null, string anchorTitle = null,
            string anchorOnClick = null)
        {
            var urlHelper = new UrlHelper(html.ViewContext.RequestContext);

            string imgUrl = urlHelper.Content(imgSrc);
            TagBuilder imgTagBuilder = new TagBuilder("img");
            imgTagBuilder.MergeAttribute("src", imgUrl);
            if (!string.IsNullOrEmpty(imgAlt))
                imgTagBuilder.MergeAttribute("alt", imgAlt);
            if(!string.IsNullOrEmpty(imgClass))
                imgTagBuilder.MergeAttribute("class", imgClass);
            string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing);

            string url = urlHelper.Action(actionName, controllerName);

            TagBuilder tagBuilder = new TagBuilder("a")
            {
                InnerHtml = img
            };

            if (string.IsNullOrEmpty(anchorOnClick))
                tagBuilder.MergeAttribute("href", url);

            if (!string.IsNullOrEmpty(anchorTitle))
                tagBuilder.MergeAttribute("title", anchorTitle);

            if (!string.IsNullOrEmpty(anchorOnClick))
                tagBuilder.MergeAttribute("OnClick", anchorOnClick);

            if (!string.IsNullOrEmpty(anchorClass))
                tagBuilder.MergeAttribute("class", anchorClass);

            return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
        }
    }