如何在 Asp.Net MVC 中创建 Image Action Link Html 助手?

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

如何在 asp.net mvc 中创建动作图像 html 助手,如下所示..

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

类似下面的助手...

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

提前致谢......

试试这个 custom Html helper:

public static IHtmlString ImageActionLink(this HtmlHelper htmlHelper, string linkText, string action, string controller, object routeValues, object htmlAttributes,string imageSrc)
{
                var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
                var img = new TagBuilder("img");
                img.Attributes.Add("src", VirtualPathUtility.ToAbsolute(imageSrc));
                var anchor = new TagBuilder("a") { InnerHtml = img.ToString(TagRenderMode.SelfClosing) };
                anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
                anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));

                return MvcHtmlString.Create(anchor.ToString());

}

您可以创建自定义助手 class,例如..

 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);
         } 
    } 
}

要使此助手在您的视图中可用,请按如下方式添加其命名空间:

@using MyNamespace

现在您可以在您的视图中获得 html 助手,如下所示...

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