Asp.net-Mvc

ActionLink MVC 中的圖像按鈕

  • May 6, 2020

如何在 ActionLink 按鈕中放置圖像而不是文本:

@Html.ActionLink("Edit-link", "Edit", new { id=use.userID })

那麼如何將文本“編輯連結”更改為圖像?

感謝您的任何想法。

這樣做:

<a href="@Url.Action("Edit")" id="@use.userID">
<img src="@Url.Content("~/images/someimage.png")" />
</a>

或通過使用其他覆蓋傳遞動作控制器名稱:

<a href="@Url.Action("Edit","Controller")" id="@use.userID">
   <img src="@Url.Content("~/images/someimage.png")" />
   </a>

更新:

您還可以創建自定義 Html Helper,並可以在應用程序中的任何視圖中重用它:

namespace MyApplication.Helpers
{
 public static class CustomHtmlHelepers
 {
   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());

   }
 }
}

並在視圖中使用它:

@using MyApplication.Helpers;

@Html.ImageActionLink("LinkText","ActionName","ControllerName",null,null,"~/images/untitled.png")

輸出 HTML:

<a href="/ControllerName/ActionName">
 <img src="/images/untitled.png">
</a>

引用自:https://stackoverflow.com/questions/23535704