【问题标题】:Create an ActionLink with HTML elements in the link text在链接文本中创建带有 HTML 元素的 ActionLink
【发布时间】:2008-12-31 09:34:48
【问题描述】:

在 ASP.NET MVC 视图中,我想包含以下形式的链接:

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

尝试在对Html.ActionLink() 的调用的linkText 字段中包含&lt;span&gt; 元素最终会被编码(正如预期的那样)。

有没有推荐的方法来实现这一点?

【问题讨论】:

    标签: asp.net-mvc actionlink


    【解决方案1】:

    您可以使用 Url.Action 为您构建链接:

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

    或使用 Html.BuildUrlFromExpression:

    <a href="<% =Html.BuildUrlFromExpression<Controller>(c => c.Action()) %>">text <span>text</span></a>
    

    【讨论】:

    • 应该注意Html.BuildUrlFromExpression 当前在 MVC Futures 程序集中,因此在 Beta 的标准安装中不可用。
    【解决方案2】:

    如果你喜欢使用 Razor,这应该可以:

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

    【讨论】:

    • 这显然是一个更新的答案
    【解决方案3】:

    另一种选择是像往常一样使用 HTML.ActionLink 或 Ajax.ActionLink(取决于您的上下文)将您的操作链接呈现到 MvcHtmlString,然后编写一个采用呈现的 MvcHtmlString 并破解您的 html 链接文本的类直接进入已经渲染好的MvcHtmlString,并返回另一个MvcHtmlString。

    所以这是执行此操作的类:[请注意插入/替换代码非常简单,您可能需要加强它以处理更多嵌套的 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);
            }
        }
    }
    

    然后你会像这样在视图中使用它:

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

    这种方法的优点是不必重现/理解标签渲染过程。

    【讨论】:

      猜你喜欢
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 2011-08-29
      • 1970-01-01
      • 2019-04-29
      • 1970-01-01
      • 1970-01-01
      • 2018-02-25
      相关资源
      最近更新 更多