我最终得到了一个自定义扩展方法。值得注意的是,当尝试将HTML放在Anchor对象内部时,链接文本可以在内部HTML的左侧或右侧。因此,我选择为左右内部HTML提供参数-链接文本位于中间。左右内部HTML都是可选的。
扩展方法ActionLinkInnerHtml:
public static MvcHtmlString ActionLinkInnerHtml(this HtmlHelper helper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues = null, IDictionary<string, object> htmlAttributes = null, string leftInnerHtml = null, string rightInnerHtml = null)
{
// CONSTRUCT THE URL
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext);
var url = urlHelper.Action(actionName: actionName, controllerName: controllerName, routeValues: routeValues);
// CREATE AN ANCHOR TAG BUILDER
var builder = new TagBuilder("a");
builder.InnerHtml = string.Format("{0}{1}{2}", leftInnerHtml, linkText, rightInnerHtml);
builder.MergeAttribute(key: "href", value: url);
// ADD HTML ATTRIBUTES
builder.MergeAttributes(htmlAttributes, replaceExisting: true);
// BUILD THE STRING AND RETURN IT
var mvcHtmlString = MvcHtmlString.Create(builder.ToString());
return mvcHtmlString;
}
使用示例:
这是用法示例。对于此示例,我只想要链接文本右侧的内部html ...
@Html.ActionLinkInnerHtml(
linkText: "Hello World"
, actionName: "SomethingOtherThanIndex"
, controllerName: "SomethingOtherThanHome"
, rightInnerHtml: "<span class=\"caret\" />"
)
结果:
这导致以下HTML ...
<a href="/SomethingOtherThanHome/SomethingOtherThanIndex">Hello World<span class="caret" /></a>