我正在尝试为我的MVC3解决方案实现一个菜单。在这个菜单中,我有两种链接:
示例1:action =“Studies”+ controller =“Main”
示例2:action =“Contact”+ controller =“Main”
示例3:action =“List”+ controller =“Project”+ routeValues = 新{category =“BANK”}
示例4:action =“List”+ controller =“Project”+ routeValues = 新{category =“PHARMA”}
菜单显示如下:
我想根据活动页面选择当前活动的菜单项。为此,我实现了一个像这样的htmlHelper:
public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
var route = htmlHelper.ViewContext.RequestContext.RouteData;
var controller = route.GetRequiredString("controller");
var action = route.GetRequiredString("action");
// some code here...
if ((controller == controllerName) && (action == actionName))
{
tag.AddCssClass("active");
}
else
{
tag.AddCssClass("inactive");
}
// some code here...
}
此基本实现的问题是激活/取消激活菜单项的条件仅基于操作和控制器值。我还需要检查我的routeValues中的“复杂链接”(例3和4)。
我该如何实现?
感谢您的帮助。
答案 0 :(得分:1)
public static MvcHtmlString ActionMenuItem(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, object routeValues, object htmlAttributes)
{
var route = htmlHelper.ViewContext.RequestContext.RouteData;
var rvd = HtmlHelper.AnonymousObjectToHtmlAttributes(routeValues);
// some code here...
if (IsRouteValuesMatch(rvd, route))
{
tag.AddCssClass("active");
}
else
{
tag.AddCssClass("inactive");
}
// some code here...
}
private static bool IsRouteValuesMatch(RouteValueDictionary rvd, RouteData routeData)
{
foreach (var item in rvd)
{
var value1 = item.Value as string;
var value2 = routeData.Values[item.Key] as string;
if (!string.Equals(value1, value2, StringComparison.OrdinalIgnoreCase))
{
return false;
}
}
return true;
}