How do you set the title attribute of an ASP.NET MVC Html.ActionLink to the generated URL
Asked Answered
S

3

6

I would like users to be able to see the corresponding URL for an anchor tag generated by Html.ActionLink() when they hover over the link. This is done by setting the title attribute but where I'm stuck is figuring out how to get that value:

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

How can I specify the URL that ActionLink is going to generate? I could hardcode something I guess but that violates DRY.

Superannuate answered 21/12, 2010 at 22:21 Comment(0)
M
5

You could use Url.Action() to generate the Link or you could Create a Custom Helper Method like this:

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

Now basically you will simply need to call your new ActionLinkHelper like this

<%= Html.ActionLinkWithTitle(@testrun.Name, "Download", "Trx", 
                 new { path = @testrun.TrxPath }) %>
Montalvo answered 21/12, 2010 at 22:36 Comment(0)
J
4

It is possible to solve jQuery.

<script type="text/javascript">
    $(function () {
        $(selector).each(function () {
            $(this).attr("title", $(this).attr("href"));
        });
    });
</script>
Jermyn answered 22/12, 2010 at 5:48 Comment(0)
W
2

The Url.Action() method should work

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

But I'm not sure if there's a better way.

Winger answered 21/12, 2010 at 22:30 Comment(1)
But doesn't satisfy DRY - you'll need to do this new { title = Url.Action("Download", "Trx") } for each link.Trichome

© 2022 - 2024 — McMap. All rights reserved.