7

I decided primarily for SEO reasons to add the "rel" to my action link, but am not sure that the way I have gone about this is going to follow "best practices." I simply created a new Extension method as shown below.

Is this the best way to go about doing this? Are there things that should be modified in this approach?

VIEW

<%= Html.ActionLink("Home", "Index", "Home")
    .AddRel("me")
    .AddTitle("Russell Solberg")
%>

EXTENSION METHODS

public static string AddRel(this string link, string rel)
{
    var tempLink = link.Insert(link.IndexOf(">"), String.Format(" rel='{0}'", rel));
    return tempLink;
}

public static string AddTitle(this string link, string title)
{
    var tempLink = link.Insert(link.IndexOf(">"), String.Format(" title='{0}'", title));
    return tempLink;
}
Lance Roberts
  • 22,383
  • 32
  • 112
  • 130
RSolberg
  • 26,821
  • 23
  • 116
  • 160

3 Answers3

13

You can add any extra html parameter very easily and don't need to write your own extension methods

<%= Html.ActionLink("Home", "Index", "Home", null,
                     new { title="Russell Solberg", rel="me"}) %>
Andy West
  • 12,302
  • 4
  • 34
  • 52
Richard Garside
  • 87,839
  • 11
  • 80
  • 93
4

You can add attributes to the action link with anonymous class passed as fourth parameter:

<%= Html.ActionLink("Home", "Index", null,new{ @title="Russell Solberg", @rel="me" }) %>

The @ sign is used to allow you to specify attribute names that are c# reserved keywordk (like class).

Branislav Abadjimarinov
  • 5,101
  • 3
  • 35
  • 44
  • I didn't know about using the @ character. I would get an error when setting more than one attribute when not using it. – Sambo Oct 13 '11 at 11:28
2

I would probably not do it that way as that will make this possible for any string. You can already do this with the action link without creating your own extensions methods. Like this:

<%=Html.ActionLink("Home", "Index", "Home", null, new {title = "Russell Solberg", rel = "me"}) %>

Personally I prefer to use Url.Action() and write the <a /> tag myself as I think thats more readable.

Mattias Jakobsson
  • 8,207
  • 2
  • 34
  • 41