When you create a new MVC project it creates a Site.master with the following markup:
public ActionResult SignIn(User user)
{
User u = db.Users.Where(p=>p.Email == user.Email & p.Password == user.Password).FirstOrDefault();
if (u == null)
{
return View();
}
var id = u.Id;
Session["id_user"] = id;
return RedirectToAction("Index", "Home");
}
You could do this by using "data-" attributes to identify the container(s) then using jQuery change CSS class of the link, like the following:
<div class="..." data-navigation="true">
<ul class="...">
<li>@Html.ActionLink("About", "About", "Home")</li>
<li>@Html.ActionLink("Contact", "Contact", "Home")</li>
</ul>
</div>
<script>
$(function () {
$("div[data-navigation='true']").find("li").children("a").each(function () {
if ($(this).attr("href") === window.location.pathname) {
$(this).parent().addClass("active");
}
});
});
</script>
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 <li>
element.
I'm putting my code here hoping it will help someone in the future:
Here's the helper method:
/// <summary>
/// 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.
/// </summary>
/// <param name="selectedClass">The CSS class that will be applied to the selected link</param>
/// <param name="otherActions">A list of tuples containing pairs of Action Name and Controller Name respectively</param>
public static MvcHtmlString NavLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string parentElement, string selectedClass, IEnumerable<Tuple<string, string>> 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:
<ul>
@Html.NavLink("Check your eligibility", "CheckEligibility", "Eligibility", "li", "current-page", new Tuple<string, string>[]
{
new Tuple<string, string>("Index", "Eligibility"),
new Tuple<string, string>("RecheckEligibility", "Eligibility")
})
@Html.NavLink("Apply for my loan", "Apply", "Loan", "li", "current-page")
</ul>