34

In an ASP.NET MVC view I'd like to include a link of the form:

<a href="blah">Link text <span>with further descriptive text</span></a>

Trying to include the <span> element in the linkText field of a call to Html.ActionLink() ends up with it being encoded (as would be expected).

Are there any recommended ways of achieving this?

sharptooth
  • 167,383
  • 100
  • 513
  • 979
Giraffe
  • 1,993
  • 3
  • 20
  • 20

3 Answers3

52

You could use Url.Action to build the link for you:

<a href="<% =Url.Action("Action", "Controller")%>">link text <span>with further blablah</span></a>

or use Html.BuildUrlFromExpression:

<a href="<% =Html.BuildUrlFromExpression<Controller>(c => c.Action()) %>">text <span>text</span></a>
Casper
  • 1,242
  • 1
  • 11
  • 12
  • Should be noted that `Html.BuildUrlFromExpression` is currently in the MVC Futures assembly and therefore not available in a standard install of the Beta. – Giraffe Dec 31 '08 at 12:04
42

if you like using Razor, this should work:

<a href="@Url.Action("Action", "Controller")">link text <span>with further blablah</span></a>
dplante
  • 2,445
  • 3
  • 21
  • 27
0

Another option is to render your action link to an MvcHtmlString as per normal, using either HTML.ActionLink, or Ajax.ActionLink (depending on your context), then write a class that takes the rendered MvcHtmlString and hacks your html link text directly into the already rendered MvcHtmlString, and returns another MvcHtmlString.

So this is the class that does that: [please note that the insertion/substitution code is VERY simple, and you may need to beef it up to handle more nested html]

namespace Bonk.Framework
{
    public class CustomHTML
    {
        static public MvcHtmlString AddLinkText(MvcHtmlString htmlString, string linkText)
        {
            string raw = htmlString.ToString();

            string left = raw.Substring(0, raw.IndexOf(">") + 1);
            string right = raw.Substring(raw.LastIndexOf("<"));

            string composed = left + linkText + right;

            return new MvcHtmlString(composed);
        }
    }
}

And then you would use it in the view like this:

@Bonk.Framework.CustomHTML.AddLinkText(Ajax.ActionLink("text to be replaced", "DeleteNotificationCorporateRecipient"), @"Link text <span>with further descriptive text</span>")

This approach has the advantage of not having to reproduce/understand the tag-rendering process.

david.barkhuizen
  • 5,239
  • 4
  • 36
  • 38