我正在尝试创建 Html.ActionLink(...) HtmlHelper 的简单自定义版本
我想向传入的 htmlAttributes 匿名对象附加一组额外的属性。
public static MvcHtmlString NoFollowActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
var customAttributes = new RouteValueDictionary(htmlAttributes) {{"rel", "nofollow"}};
var link = htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, customAttributes);
return link;
}
所以在我看来我会这样:
@Html.NoFollowActionLink("Link Text", "MyAction", "MyController")
我希望呈现出如下链接:
<a href="/MyController/MyAction" rel="nofollow">Link Text</a>
但我得到的是:
<a href="/MyController/MyAction" values="System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Object]" keys="System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Object]" count="1">Link Text</a>
我已经尝试了各种方法将匿名类型转换为 RouteValueDictionary,添加到它然后将其传递给根 ActionLink(...) 方法或转换为字典,或使用 HtmlHelper.AnonymousObjectToHtmlAttributes 并执行相同但似乎没有任何效果。
最佳答案
你得到的结果就是这个来源造成的code :
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
return ActionLink(htmlHelper, linkText, actionName, controllerName, TypeHelper.ObjectToDictionary(routeValues), HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));
}
如你所见HtmlHelper.AnonymousObjectToHtmlAttributes
被称为内部。这就是为什么你得到 values
和 keys
当你通过它时RouteValueDictionary
对象。
只有两种方法符合您的参数列表:
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, RouteValueDictionary routeValues, IDictionary<string, object> htmlAttributes)
第二个重载不会对您的参数做任何事情,只是传递它们。 您需要修改代码以调用其他重载:
public static MvcHtmlString NoFollowActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues = null, object htmlAttributes = null)
{
var routeValuesDict = new RouteValueDictionary(routeValues);
var customAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (!customAttributes.ContainsKey("rel"))
customAttributes.Add("rel", "nofollow");
return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValuesDict, customAttributes);
}
当你通过 routeValues
作为RouteValueDictionary
选择了另一个重载(RouteValueDictionary
正在实现 IDictionary<string, object>
所以没问题),并且返回的链接是正确的。
如果rel
属性将已经存在于 htmlAttributes
中对象,将抛出异常:
System.ArgumentException: An item with the same key has already been added.
关于c# - 添加到自定义 ActionLink 帮助程序扩展的 htmlAttributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21188570/