One easy way to do is using BaseController
ViewData["ActivePage"] = ActivePage();
private string ActivePage()
{
string actionName = this.ControllerContext
.RouteData
.Values["action"]
.ToString();
string controllerName = this.ControllerContext
.RouteData
.Values["controller"]
.ToString();
return string.Format($"{controllerName}-{actionName}");
}
You can call active page before action executing. After this you need to check this ViewData on Layout page.
$(document).ready(function () {
var activePageName = '@ViewData["ActivePage"]';
var activeElement = $('li.' + activePageName);
activeElement.addClass('active');
$.each(activeElement.parents('li'), function (k, v) {
$(v).addClass('active');
});
});
And before script your ul and li element must contains specific name to recognize it. You need to use format given in BaseController ActivePage method
ControlleName-ActionName.
<ul class="nav nav-second-level collapse">
<li class="Home-Index">
@Html.ActionLink("Index", "Index", "Home")
</li>
</ul>