如何将ASP.NET MVC Html.ActionLink的标题属性设置为生成的URL

5

我希望用户在悬停链接时能够看到Html.ActionLink()生成的锚标记的相应URL。这是通过设置title属性来完成的,但我卡在了如何获取该值上:

@Html.ActionLink(@testrun.Name, "Download", "Trx", 
                 new { path = @testrun.TrxPath }, new { title = ??)

我该如何指定ActionLink生成的URL?我猜可以硬编码,但这违反了DRY
3个回答

5
您可以使用Url.Action()生成链接,也可以创建自定义助手方法,如下所示:
public static class HtmlHelpers {
    public static MvcHtmlString ActionLinkWithTitle(this HtmlHelper helper, 
                                                    string linkText, 
                                                    string actionName, 
                                                    object routeValues) {
       return helper.ActionLink(linkText, actionName, routeValues, 
              new {title = Url.Action(linkText, actionName, routevalues )
    }
}

现在,您只需要像这样调用您的新ActionLinkHelper即可。
<%= Html.ActionLinkWithTitle(@testrun.Name, "Download", "Trx", 
                 new { path = @testrun.TrxPath }) %>

4
可以解决jQuery问题。
<script type="text/javascript">
    $(function () {
        $(selector).each(function () {
            $(this).attr("title", $(this).attr("href"));
        });
    });
</script>

2

Url.Action() 方法应该可以正常工作。

@Html.ActionLink(@testrun.Name, "Download", "Trx", 
             new { path = @testrun.TrxPath }, new { title = Url.Action("Download", "Trx") })

但我不确定是否有更好的方法。


但是不符合DRY原则 - 每个链接都需要执行new { title = Url.Action("Download", "Trx") } - Michael Shimmins

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接