添加到自定义ActionLinkHelper扩展的htmlAttributes传入的htmlAttributes匿名对象附加一组额外的属性。publicstaticMvcHtmlStringNoFollowActionLink(thisHtmlHelperhtmlHelper,stringlinkText,stringactionName,stringcontrollerName,objectrouteValues,objecthtmlAttributes){varcustomAttributes=newRouteValueDictionary(htmlAttributes){{"rel","nofollow"}};HvarActionLink(linkText,actionName,controllerName,routeValues,customAttributes);返回链接;所以在我看来我会这样做:@Html.NoFollowActionLink("LinkText","MyAction","MyController")我希望它呈现这样的链接:LinkText但我得到的是:LinkTextI've尝试了将匿名类型转换为RouteValueDictionary的各种方法,将其添加到其中然后将其传递给根ActionLink(...)方法或转换为字典,或使用HtmlHelper.AnonymousObjectToHtmlAttributes并执行相同但似乎没有工作。您得到的结果是由以下源代码引起的:ObjectToDictionary(routeValues),HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes));如您所见,内部调用了HtmlHelper.AnonymousObjectToHtmlAttributes。这就是为什么在传递RouteValueDictionary对象时会得到值和键。只有两种方法匹配你的参数列表:,IDictionaryhtmlAttributes)第二个重载对您的参数没有任何作用,只是传递它们。你需要修改你的代码来调用其他的重载:)=HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);如果(!customAttributes.ContainsKey("rel"))customAttributes.Add("rel","nofollow");返回htmlHelper.ActionLink(linkText,actionName,controllerName,routeValuesDict,customAttributes);当你将routeValues作为RouteValueDictionary传递时,选择了另一个重载(RouteValueDictionary正在实现IDictionary所以没问题),并且返回的链接是正确的。如果htmlAttributes对象中已存在rel属性,则抛出异常:System.ArgumentException:已添加具有相同键的项目。当您想更新接收到的htmlAttributes对象以添加新属性(rel)时,您需要将匿名htmlAttributes对象转换为IDictionary(因为您无法向匿名对象添加新属性)。这意味着您需要调用此ActionLink方法的重载,该方法还需要将匿名routeValues转换为RouteValueDictionary。您可以使用新的RouteValueDictionary(routeValues)轻松转换路由值。要转换html属性,您需要像这个问题中那样的一些反射逻辑。(正如slawek在他的回答中已经提到的,您还可以利用已经实现为字典的RouteValueDictionary并以相同的方式转换htmlAttributes)最后您的扩展将是这样的:publicstaticMvcHtmlStringNoFollowActionLink(thisHtmlHelperhtmlHelper,stringlinkText,stringactionName,stringcontrollerName,objectrouteValues=null,objecthtmlAttributes=null){varhtmlAttributesDictionary=newDictionary();if(htmlAttributes!=null){foreach(varpropinhtmlAttributes.GetType().GetProperties(BindingFlags.Instance|BindingFlags.Public)){htmlAttributesDictionary.Add(prop.Name,prop.GetValue(htmlAttributes,null));}}htmlAttributesDictionary["rel"]="nofollow";varrouteValuesDictionary=newRouteValueDictionary(routeValues);varlink=htmlHelper.ActionLink(linkText,actionName,controllerName,routeValuesDictionary,htmlAttributesDictionary);返回链接;如果你这样称呼它:@Html.NoFollowActionLink("LinkText","MyAction","MyController",new{urlParam="param1"},new{foo="dummy"})你会得到下面的html:链接文字请注意,由于rel属性是在原始属性添加到字典后添加/更新的,因此即使调用者为属性指定了另一个值,它也会始终强制执行rel="nofollow"希望有帮助!以上是C#学习教程:添加到htmlAttributes中,获取自定义ActionLinkhelperextension共享的所有内容。如果对你有用,需要进一步了解C#学习教程,希望大家多多关注。本文来自网络收集,不代表任何内容,如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
