C# 扩展HtmlHelper RouteLink
我已经有很长一段时间在痛击自己的头了,我很确定我错过了一些非常明显的东西。我想创建一个路由链接,如果当前控制器操作与之匹配,它可以动态地将css类设置为“selected”。然而,这很容易,我在修改需要传递的现有htmlAttributes时遇到了麻烦C# 扩展HtmlHelper RouteLink,c#,asp.net-mvc,C#,Asp.net Mvc,我已经有很长一段时间在痛击自己的头了,我很确定我错过了一些非常明显的东西。我想创建一个路由链接,如果当前控制器操作与之匹配,它可以动态地将css类设置为“selected”。然而,这很容易,我在修改需要传递的现有htmlAttributes时遇到了麻烦 public static MvcHtmlString RouteLinkSelectable(this HtmlHelper html, string linkText, string routeName, object routeValues
public static MvcHtmlString RouteLinkSelectable(this HtmlHelper html, string linkText, string routeName, object routeValues, object htmlAttributes, string controller = null, string action = null)
{
// omitting code for determining if the class should be set, because it
// doesn't modify the behavior. It does that same thing with the following code
var myAttributes = new Dictionary<string, object>
{
{ "data-myattribute1", "value1" },
{ "data-myattribute2", "value2" }
};
var attributes = new RouteValueDictionary(htmlAttributes);
// now merge them with the user attributes
foreach (var item in attributes)
{
// remove this test if you want to overwrite existing keys
if (!myAttributes.ContainsKey(item.Key))
{
myAttributes[item.Key] = item.Value;
}
}
return html.RouteLink(linkText, routeName, routeValues, myAttributes);
}
它产生以下输出:
<a Comparer="System.Collections.Generic.GenericEqualityComparer`1[System.String]" Count="3" Keys="System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Object]" Values="System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Object]" href="/">profil</a>
如果我修改代码以使用经典语法(..,new{id=“lnkProfile”})
,则效果良好。如果我创建了一个具有属性的新类,它会很好地工作。如果我使用expando对象,它不会附加任何html属性。。。如果尝试使用字典,结果如上图所示。。。拜托,有人能给我解释一下,为什么会这样,我怎么解决
顺便说一句,我当然可以从头创建一个链接,但是当我只需要动态添加一个html属性时,为什么要重新设计这个轮子呢?问题是,您针对的RouteLink重载错误,请使用以下命令更改return语句
return html.RouteLink(linkText, routeName, new RouteValueDictionary(routeValues), myAttributes);
有趣的是,这似乎有效,但为什么呢?我通常使用该重载,当我将其指定为“new{….}”时,我不需要更改任何内容。。我觉得很奇怪。不管怎样,谢谢你解决这个问题。。如果你能进一步解释为什么它的行为不同,我会很高兴,但我将此标记为一个答案。在routeValues是RouteValueDictionary,htmlAttributes是IDictionary的情况下使用重载,或者在routeValues和htmlAttributes都是匿名对象的情况下使用另一个重载。在你的第一个方法中,你把它们混在一起了。
return html.RouteLink(linkText, routeName, new RouteValueDictionary(routeValues), myAttributes);