Create an ActionLink with HTML elements in the link text
Asked Answered
U

3

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?

Undermine answered 31/12, 2008 at 9:34 Comment(0)
O
53

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>
Overunder answered 31/12, 2008 at 11:28 Comment(1)
Should be noted that Html.BuildUrlFromExpression is currently in the MVC Futures assembly and therefore not available in a standard install of the Beta.Undermine
C
42

if you like using Razor, this should work:

<a href="@Url.Action("Action", "Controller")">link text <span>with further blablah</span></a>
Costotomy answered 17/9, 2012 at 15:21 Comment(1)
this is obviously a much more recent answerSeptal
T
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.

Twelvemonth answered 16/11, 2012 at 8:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.