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

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

尝试将<span>元素包含在对linkText的调用的Html.ActionLink()字段中,最终会对其进行编码(如预期的那样)。

有没有推荐的方法来实现这个目标?

有帮助吗?

解决方案

您可以使用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>

其他提示

如果您喜欢使用Razor,这应该可行:

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

另一种选择是使用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>")

这种方法的优点是无需重现/理解标签呈现过程。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top