Asp.net-Mvc-3

原始 ActionLink 連結文本

  • September 15, 2014

我想把一個按鈕作為一個文本,@ActionLink()但我不能,因為它 HTML 轉義了我的字元串……我找到了@Html.Raw()機制並嘗試了@ActionLink().ToHtmlString()但無法弄清楚如何將它放在一起……

我發現一篇文章描述了為類似目的建構擴展,但是遇到這麼多麻煩是令人討厭的……必須有一個簡單的方法嗎?

你可以寫一個助手:

public static class HtmlExtensions
{
   public static IHtmlString MyActionLink(
       this HtmlHelper htmlHelper, 
       string linkText, 
       string action, 
       string controller,
       object routeValues,
       object htmlAttributes
   )
   {
       var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
       var anchor = new TagBuilder("a");
       anchor.InnerHtml = linkText;
       anchor.Attributes["href"] = urlHelper.Action(action, controller, routeValues);
       anchor.MergeAttributes(new RouteValueDictionary(htmlAttributes));
       return MvcHtmlString.Create(anchor.ToString());
   }
}

然後使用這個助手:

@Html.MyActionLink(
   "<span>Hello World</span>", 
   "foo", 
   "home",
   new { id = "123" },
   new { @class = "foo" }
)

給定的預設路由將產生:

<a class="foo" href="/home/foo/123"><span>Hello World</span></a>

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