我已经为 HtmlHelper(派生自 active menu item - asp.net mvc3 master page)编写了一个扩展方法。这允许我为当前页面输出 cssclass“active”。
但是,我现在已经重构为使用区域,因此该方法不再有效,因为我在多个区域中有名为 Home 的 Controller 和名为 Index 的操作。所以我一直在尝试通过检查当前区域来解决这个问题,其中 Area 作为 routevalues 匿名类型的一部分传递。
所以我的扩展方法现在看起来像这样:
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 的类型更改为动态,以便我可以编译以下行:
string area = routeValues.Area;
我可以在调试器中的 routeValues 对象上看到 Area 属性,但一旦访问它,我就会收到 RuntimeBinderException。
有没有更好的方法来访问匿名类型的属性?
最佳答案
我发现我可以在 RouteValueDictionary 上使用构造函数,这使我可以轻松地查找 Area
属性。
我还注意到,我还尝试使用 Controller 值使问题复杂化,因此我的代码现在如下所示:
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;
}
关于asp.net-mvc-3 - ASP.NET MVC3 : How to get access to parameters passed as routeValues anonymous type in a HtmlHelper extension method?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5008927/