【发布时间】:2016-07-08 11:34:18
【问题描述】:
我正在使用扩展方法在菜单上的活动链接上维护一个 css 类。
但是我遇到了一个问题,即 htmlAttributes 和对象值导致错误。
我的 Razor 页面中有以下内容,但我不明白我是如何解析 htmlAttributes 的。
@Html.MenuLink("Summary", "Summary", "Graphs", null, new { @class = "dropdown-toggle caret", data_target = "#", data_toggle = "dropdown" })
通过查看 HtmlHelper,该方法应该将 IDictionary<object, string> 作为 htmlAttributes 的类型。新的{ @class = "dropdown-toggle caret", data_target = "#", data_toggle = "dropdown" } 语法不是字典的典型语法,所以这是正确的吗?
显然我做错了什么,因为它返回以下错误:
Argument 6: cannot convert from '<anonymous type: string class, string data_target, string data_toggle>' to 'System.Collections.Generic.IDictionary<object, string>'
我正在尝试的扩展方法如下:
public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper, string text, string action, string controller, RouteValueDictionary routeValues, IDictionary<object, string> htmlAttributes)
{
var routeData = htmlHelper.ViewContext.RouteData.Values;
var currentController = routeData["controller"];
var currentAction = routeData["action"];
if (string.Equals(action, currentAction as string, StringComparison.OrdinalIgnoreCase) &&
string.Equals(controller, currentController as string, StringComparison.OrdinalIgnoreCase))
{
return htmlHelper.ActionLink(text, action, controller, null, new { @class = "currentMenu" });
}
return htmlHelper.ActionLink(text, action, controller);
}
【问题讨论】:
标签: asp.net-mvc razor html-helper