Question

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?

Was it helpful?

Solution

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>

OTHER TIPS

if you like using Razor, this should work:

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

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top