When you create a new MVC project it creates a Site.master with the following markup:
Thanks to @codingbadger for the solution.
I had to get my nav-links highlighted on multiple actions so I decided to add a few more parameters that contain the controller-action pairs and it'll highlight the link if either of those combinations is accessed too. And, in my case, the highlighting class was to be applied to a element.
I'm putting my code here hoping it will help someone in the future:
Here's the helper method:
///
/// The link will be highlighted when it is used to redirect and also be highlighted when any action-controller pair is used specified in the otherActions parameter.
///
/// The CSS class that will be applied to the selected link
/// A list of tuples containing pairs of Action Name and Controller Name respectively
public static MvcHtmlString NavLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string parentElement, string selectedClass, IEnumerable> otherActions)
{
string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
if ((actionName == currentAction && controllerName == currentController) ||
(otherActions != null && otherActions.Any(pair => pair.Item1 == currentAction && pair.Item2 == currentController)))
{
return new MvcHtmlString($"<{parentElement} class=\"{selectedClass}\">{htmlHelper.ActionLink(linkText, actionName, controllerName)}{parentElement}>");
}
return new MvcHtmlString($"<{parentElement}>{htmlHelper.ActionLink(linkText, actionName, controllerName)}{parentElement}>");
}
And, here's an example of how to use it:
@Html.NavLink("Check your eligibility", "CheckEligibility", "Eligibility", "li", "current-page", new Tuple[]
{
new Tuple("Index", "Eligibility"),
new Tuple("RecheckEligibility", "Eligibility")
})
@Html.NavLink("Apply for my loan", "Apply", "Loan", "li", "current-page")