Raw ActionLink linkText

ekk*_*kis 9 html-helper actionlink razor asp.net-mvc-3

我想把一个按钮作为文本,@ActionLink()但我不能,因为它HTML转义我的字符串......我找到了@Html.Raw()机制,并尝试了@ActionLink().ToHtmlString()但无法弄清楚如何把它放在一起...

我找到了一篇文章,描述了为类似目的构建扩展,但是为了解决这个问题真是太过分了......必须有一个简单的方法吗?

Dar*_*rov 13

你可以写一个帮手:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后使用这个帮助器:

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

给出默认路线会产生:

<a class="foo" href="/home/foo/123"><span>Hello World</span></a>
Run Code Online (Sandbox Code Playgroud)

  • 但老实说,就此而言,我只能做`<a href='@Url.Action()'>无论什么</a>'` (3认同)