asp.net-mvc 在链接文本中使用 HTML 元素创建 ActionLink
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/402605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create an ActionLink with HTML elements in the link text
提问by Giraffe
In an ASP.NET MVC view I'd like to include a link of the form:
在 ASP.NET MVC 视图中,我想包含以下形式的链接:
<a href="blah">Link text <span>with further descriptive text</span></a>
Trying to include the <span>element in the linkTextfield of a call to Html.ActionLink()ends up with it being encoded (as would be expected).
尝试将<span>元素包含在linkText调用的字段中,Html.ActionLink()最终会对其进行编码(正如预期的那样)。
Are there any recommended ways of achieving this?
有没有推荐的方法来实现这一目标?
回答by Casper
You could use Url.Action to build the link for you:
您可以使用 Url.Action 为您构建链接:
<a href="<% =Url.Action("Action", "Controller")%>">link text <span>with further blablah</span></a>
or use Html.BuildUrlFromExpression:
或使用 Html.BuildUrlFromExpression:
<a href="<% =Html.BuildUrlFromExpression<Controller>(c => c.Action()) %>">text <span>text</span></a>
回答by dplante
if you like using Razor, this should work:
如果你喜欢使用 Razor,这应该有效:
<a href="@Url.Action("Action", "Controller")">link text <span>with further blablah</span></a>
回答by david.barkhuizen
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.
另一种选择是按照正常方式使用 HTML.ActionLink 或 Ajax.ActionLink(取决于您的上下文)将您的操作链接呈现到 MvcHtmlString,然后编写一个类,该类采用呈现的 MvcHtmlString 并将您的 html 链接文本直接破解到已经呈现 MvcHtmlString,并返回另一个 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]
所以这是执行此操作的类:[请注意插入/替换代码非常简单,您可能需要加强它以处理更多嵌套的 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.
这种方法的优点是不必重现/理解标签渲染过程。

