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

前端 未结 8 2333
误落风尘
误落风尘 2020-12-01 08:42

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

8条回答
  •  鱼传尺愫
    2020-12-01 09:08

    this code has been tested on mvc4...

        public static MvcHtmlString 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;
            var imgTag = new TagBuilder("img");
            imgTag.MergeAttribute("src", imgSrc);
            imgTag.MergeAttributes((IDictionary)imgHtmlAttributes, true);
            string url = urlHelper.Action(actionName, controllerName, routeValues);
    
    
    
            var imglink = new TagBuilder("a");
            imglink.MergeAttribute("href", url);
            imglink.InnerHtml = imgTag.ToString();
            imglink.MergeAttributes((IDictionary)htmlAttributes, true);
    
            return MvcHtmlString.Create(imglink.ToString());
    
        }
    

提交回复
热议问题