簡體   English   中英

如何在Asp.Net MVC中創建圖像動作鏈接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")

提前致謝.....

試試這個自定義的HTML幫助器

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

}

您可以創建類似的自定義幫助程序類。

 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 helper。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM