我已经为HtmlHelper编写了一个扩展方法(派生自active menu item - asp.net mvc3 master page)。这允许我输出当前页面的cssclass“active”。
但是,我现在已经重构使用区域,因此该方法不再有效,因为我在几个区域都有名为Home的控制器和名为Index的操作。所以我一直试图通过检查当前区域来解决这个问题,并将区域作为routevalues anonymous类型的一部分传递。
所以我的扩展方法现在看起来像这样:
public static MvcHtmlString NavigationLink<T>(this HtmlHelper<T> htmlHelper, string linkText, string actionName, string controllerName, dynamic routeValues)
{
string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
string currentArea = htmlHelper.ViewContext.RouteData.DataTokens["Area"] as string;
if (controllerName == currentController && IsInCurrentArea(routeValues,currentArea))
{
return htmlHelper.ActionLink(
linkText,
actionName,
controllerName,
(object)routeValues,
new
{
@class = "active"
});
}
return htmlHelper.ActionLink(linkText, actionName, controllerName, (object)routeValues, null);
}
private static bool IsInCurrentArea(dynamic routeValues, string currentArea)
{
string area = routeValues.Area; //This line throws a RuntimeBinderException
return string.IsNullOrEmpty(currentArea) && (routeValues == null || area == currentArea);
}
我将routeValues的类型更改为dynamic,以便我可以编译以下行:
string area = routeValues.Area;
我可以在调试器中的routeValues对象上看到Area属性,但是一旦我访问它,我就会得到一个RuntimeBinderException。
有没有更好的方法来访问匿名类型的属性?
答案 0 :(得分:2)
我已经发现我可以使用RouteValueDictionary上的构造函数,它允许我轻松查找Area
属性。
我还注意到我通过尝试使用控制器值使问题变得复杂,所以我的代码现在看起来如下:
public static MvcHtmlString NavigationLink<T>(this HtmlHelper<T> htmlHelper, string linkText, string actionName, string controllerName, object routeValues)
{
string currentArea = htmlHelper.ViewContext.RouteData.DataTokens["Area"] as string;
if (IsInCurrentArea(routeValues, currentArea))
{
return htmlHelper.ActionLink(
linkText,
actionName,
controllerName,
routeValues,
new
{
@class = "active"
});
}
return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, null);
}
private static bool IsInCurrentArea(object routeValues, string currentArea)
{
if (routeValues == null)
return true;
var rvd = new RouteValueDictionary(routeValues);
string area = rvd["Area"] as string ?? rvd["area"] as string;
return area == currentArea;
}