【问题标题】:How do you set the title attribute of an ASP.NET MVC Html.ActionLink to the generated URL如何将 ASP.NET MVC Html.ActionLink 的标题属性设置为生成的 URL
【发布时间】:2010-12-21 22:21:53
【问题描述】:

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

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

如何指定 ActionLink 将生成的 URL?我可以硬编码一些我猜的东西,但这违反了DRY

【问题讨论】:

    标签: c# asp.net-mvc actionlink


    【解决方案1】:

    您可以使用 Url.Action() 来生成链接,或者您可以像这样创建自定义 Helper 方法:

    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 }) %>
    

    【讨论】:

      【解决方案2】:

      可以解决jQuery。

      <script type="text/javascript">
          $(function () {
              $(selector).each(function () {
                  $(this).attr("title", $(this).attr("href"));
              });
          });
      </script>
      

      【讨论】:

        【解决方案3】:

        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") }
        猜你喜欢
        • 1970-01-01
        • 2017-11-21
        • 1970-01-01
        • 2011-05-21
        • 2011-01-11
        • 1970-01-01
        • 2014-06-17
        • 2017-01-22
        • 1970-01-01
        相关资源
        最近更新 更多