在 ASP.NET MVC 视图中,我想包含以下表单的链接:
<a href="blah">Link text <span>with further descriptive text</span></a>
尝试将<span>
元素包含在linkText
调用字段中Html.ActionLink()
最终会被编码(正如预期的那样)。
有没有推荐的方法来实现这一目标?
在 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>")
这种方法的优点是不必重现/理解标签渲染过程。