Search code examples
asp.net-mvcrouteshtml-helper

Is there an ASP.NET MVC HtmlHelper for image links?


The Html.RouteLink() HtmlHelper works great for text links. But what's the best way to link an image?


Solution

  • Here is mine, it`s the core function make some overloads

    public static string ImageLink(this HtmlHelper htmlHelper, string imgSrc, string alt, string actionName, string controllerName, object routeValues, object htmlAttributes, object imgHtmlAttributes)
    {
        UrlHelper urlHelper = ((Controller)htmlHelper.ViewContext.Controller).Url;
        string imgtag = htmlHelper.Image(imgSrc, alt,imgHtmlAttributes);
        string url = urlHelper.Action(actionName, controllerName, routeValues);
    
        TagBuilder imglink = new TagBuilder("a");
        imglink.MergeAttribute("href", url);
        imglink.InnerHtml =imgtag;
        imglink.MergeAttributes(new RouteValueDictionary(htmlAttributes), true);
    
        return imglink.ToString();
    }