如何基于主操作在部分视图上添加活动类

时间:2017-03-22 02:19:38

标签: asp.net asp.net-mvc

我试图添加"有效"在MVC中我的引导程序导航栏,但我有一个大问题。

我正在使用这个助手,但由于我将导航栏放在局部视图上,所以它不起作用,因为调用该函数的动作是_PartialViewName。

public static string IsActive(this HtmlHelper html,
    string control, string action)
{
    var routeData = html.ViewContext.RouteData;

    var routeAction = (string)routeData.Values["action"];
    var routeControl = (string)routeData.Values["controller"];

    // both must match
    var returnActive = control.ToUpper() == routeControl.ToUpper() &&
        action.ToUpper() == routeAction.ToUpper();

    return returnActive ? "active" : "";
}

有没有办法解决这个问题?无论如何,谢谢你。

1 个答案:

答案 0 :(得分:0)

我使用以下代码在多级别的bootstrap导航栏中设置活动。 你可以试试那段代码。

<script type="text/javascript">
var action = "@ViewContext.RouteData.Values["action"]";
var controller = "@ViewContext.RouteData.Values["controller"]";
var area = "@ViewContext.RouteData.DataTokens["area"]"; // use only when u have area
    var pathname = window.location.pathname.toString();
    if (pathname.indexOf(action) > -1) {
        var st = "/" + action;
       pathname= pathname.replace(new RegExp(st,'g'), '');
    }
function active(e) {
    e.addClass('active');
    if (e.closest('ul').length > 0) {
        menuOpen(e.closest('ul'));
    }
}
function menuOpen(m) {
    m.addClass('menu-open');
    if (m.closest('li').length > 0) {
        active(m.closest('li'));
    }
}
if (action != null && action == "Index" && area != "") {
    var $z = $('a[href="' + pathname + '"]').closest('li');
    active($z);
}
else if (area != null && action != "Index" && controller != "Home") {
    var $z = $('a[href="' + pathname +'/'+ action + '"]').closest('li');
    if ($z.length > 0) {
        active($z);
    }
    else {
        var $z = $('a[href="' + pathname+'"]').closest('li');
        active($z);
    }
}
else if (area == "" && controller != "Home") {
    var $z = $('a[href="' + pathname + '"]').closest('li');
    active($z);
}
else if (controller == "Home" && action == "Index") {
    var $z = $('a[href="' + pathname + '"]').closest('li').addClass('active');
}
else {
    var $z = $('a[href="' + pathname + '"]').closest('li').addClass('active');
}
</script>