问题
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?
回答1:
You could use Url.Action to build the link for you:
<a href="<% =Url.Action("Action", "Controller")%>">link text <span>with further blablah</span></a>
or use Html.BuildUrlFromExpression:
<a href="<% =Html.BuildUrlFromExpression<Controller>(c => c.Action()) %>">text <span>text</span></a>
回答2:
if you like using Razor, this should work:
<a href="@Url.Action("Action", "Controller")">link text <span>with further blablah</span></a>
回答3:
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]
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.
来源:https://stackoverflow.com/questions/402605/create-an-actionlink-with-html-elements-in-the-link-text