how to put class="active" within <li> depending on selected controller?
<li ><a href="@Url.Action("index", "Home")">Home</a></li>
<li ><a href="@Url.Action("index", "Car")">Cars</a></li>
Blessings
I generally create an action link html helper for accomplishing this task. Note, that I mark the link itself as "selected" vs the list item.
public static class ActionLinkHelpers
{
public static MvcHtmlString SelectedActionLink(this HtmlHelper helper, string linkText, string actionName, string controllerName)
{
var controller = (string) helper.ViewContext.RouteData.Values["controller"];
if (string.Compare(controller, controllerName, StringComparison.InvariantCultureIgnoreCase) == 0)
{
return helper.ActionLink(linkText, actionName, controllerName, null, new { Class = "selected" });
}
return helper.ActionLink(linkText, actionName, controllerName);
}
}
After you have an action link helper setup within your project your list would look as follows:
<li>@Html.SelectedActionLink("Home", "index", "Home")</li>
<li>@Html.SelectedActionLink("Cars", "index", "Car")</li>
EDIT:
In order to use a custom helper MVC must be aware of it. Add a new folder to your project "HtmlHelpers" for example and place this class inside of it. From there you need to add a line to the /Views/Web.config:
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="YourNameSpace.HtmlHelpers"/>
</namespaces>
</pages>