在mvc中运行时将css类应用于菜单项
我正在研究MVC4应用程序
我有以下菜单项
现在我希望如果我点击除Home之外的Items,它的css-class更改为active。 基本上我只是想改变菜单项的颜色如何动态制作?
如果要根据Action或Controller更改css,可以使用
@{ var controller = ViewContext.RouteData.Values["Controller"].ToString(); var action = ViewContext.RouteData.Values["Action"].ToString(); } @if (action == "Home") { @Html.ActionLink("Home", "Index", new { Controller = "Home" },new {@class="active" }) } else { @Html.ActionLink("Home", "Index", new { Controller = "Home" }) } @if (action == "About Us") { @Html.ActionLink("About Us", "About", new { Controller = "Home" },new {@class="active" }) } else { @Html.ActionLink("About Us", "About", new { Controller = "Home" }) }
等等…
public static class MyHtmlHelper { public static String 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"; else return String.Empty; } }
然后,您可以在视图中使用此帮助程序。
@Html.NavActive("Index", "Home")
例如,
Index