OK new to MVC. I had asked this question earlier and got an answer but I am wondering if there is a simpler solution.
Say I have a master page with a menu laid out as an
More simplest way when you don't want to change your code much
.. Thanks @Hugo Hilário for the concept
using Microsoft.Web.Mvc;
using System.Web.Mvc;
using System.Web.Mvc.Html;
namespace Demo.Web.Mvc
{
public static class UIHelper
{
public static MvcHtmlString ActivePage(this HtmlHelper helper, string linkText, string action, string controller)
{
string currentController = helper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
string currentAction = helper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
var actionLink = helper.ActionLink(linkText, action,controller);
var isCurrentRoute = currentController == controller;// && currentAction == action; uncomment if you want to segregate by action also
return MvcHtmlString.Create(string.Format("<li{0}>", isCurrentRoute ? " class=\"YourActiveCssClass\"" : string.Empty) + actionLink + "</li>");
}
}
}
Layout page
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
@Html.ActivePage("User", "Index", "User")
@Html.ActivePage("State", "Index", "State")
@Html.ActivePage("City", "Index", "City")
</ul>
</div>