创建一个在链接文本中包含 HTML 元素的 ActionLink
在 ASP.NET MVC 视图中,我想包含以下形式的链接:
<a href="blah">Link text <span>with further descriptive text</span></a>
Trying to include the element in the
linkText
field of a call to Html.ActionLink()
最终会被编码(正如预期的那样)。
有没有推荐的方法来实现这一目标?
In an ASP.NET MVC view I'd like to include a link of the form:
<a href="blah">Link text <span>with further descriptive text</span></a>
Trying to include the <span>
element in the linkText
field of a call to Html.ActionLink()
ends up with it being encoded (as would be expected).
Are there any recommended ways of achieving this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用 Url.Action 为您构建链接:
或使用 Html.BuildUrlFromExpression:
You could use Url.Action to build the link for you:
or use Html.BuildUrlFromExpression:
如果你喜欢使用 Razor,这应该可以:
if you like using Razor, this should work:
另一种选择是使用 HTML.ActionLink 或 Ajax.ActionLink(具体取决于您的上下文)将您的操作链接呈现为 MvcHtmlString,然后编写一个类,该类采用呈现的 MvcHtmlString 并将您的 html 链接文本直接写入已经呈现 MvcHtmlString,并返回另一个 MvcHtmlString。
所以这是执行此操作的类:[请注意,插入/替换代码非常简单,您可能需要加强它以处理更多嵌套的 html]
然后您将在视图中使用它,如下所示:
这种方法具有不必重现/理解标签渲染过程的优点。
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]
And then you would use it in the view like this:
This approach has the advantage of not having to reproduce/understand the tag-rendering process.