Applying Css Class To Menu Item At Run Time In Mvc
I am working on an MVC4 Application I have a following Menu Items
Solution 1:
If you want to change the css based on Action or Controller you can use
@{
var controller = ViewContext.RouteData.Values["Controller"].ToString();
var action = ViewContext.RouteData.Values["Action"].ToString();
}
<li>
@if (action == "Home") {
@Html.ActionLink("Home", "Index", new { Controller = "Home" },new {@class="active" })
}
else {
@Html.ActionLink("Home", "Index", new { Controller = "Home" })
}
</li>
<li>
@if (action == "About Us") {
@Html.ActionLink("About Us", "About", new { Controller = "Home" },new {@class="active" })
}
else {
@Html.ActionLink("About Us", "About", new { Controller = "Home" })
}
</li>
etc...
Solution 2:
publicstaticclassMyHtmlHelper{
publicstaticString NavActive(this HtmlHelper htmlHelper,
string actionName,
string controllerName)
{
var controller = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
var action = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
if (controllerName == controller && action == actionName )
return"active";
elsereturnString.Empty;
}
}
Then you can use this helper in your view.
@Html.NavActive("Index", "Home")
For instance,
<li><ahref="~/Home/Index"class="@Html.NavActive("Index", "Home")"><span>Index</span></a></li>
Post a Comment for "Applying Css Class To Menu Item At Run Time In Mvc"