Create an ActionLink with HTML elements in the link text

前端 未结 3 1423
栀梦
栀梦 2020-12-08 13:36

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

Link text with further descriptive text

        
相关标签:
3条回答
  • 2020-12-08 14:07

    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>
    
    0 讨论(0)
  • 2020-12-08 14:07

    if you like using Razor, this should work:

    <a href="@Url.Action("Action", "Controller")">link text <span>with further blablah</span></a>
    
    0 讨论(0)
  • 2020-12-08 14:16

    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.

    0 讨论(0)
提交回复
热议问题