在 ASP.NET MVC 中,向引导导航栏添加“active”类是基本的。然而,将其添加到 的常见方法是:
Bootstrap 要求将“active”类应用于
<ul class="nav navbar-nav"> <li class="active">@Html.ActionLink("Home", "Index", "Home")</li> <li>@Html.ActionLink("About", "About", "Home")</li> <li>@Html.ActionLink("Contact", "Contact", "Home")</li> </ul>
而不是手动将“活动”类添加到每个
<ul class="nav navbar-nav"> <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Index" ? "active" : "")">@Html.ActionLink("Home", "Index", "Home")</li> <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "About" ? "active" : "")">@Html.ActionLink("About", "About", "Home")</li> <li class="@(ViewContext.RouteData.Values["Action"].ToString() == "Contact" ? "active" : "")">@Html.ActionLink("Contact", "Contact", "Home")</li> </ul>
更优雅的解决方案是创建一个HtmlHelper扩展方法:
public static string IsSelected(this HtmlHelper html, string controllers = "", string actions = "", string cssClass = "selected") { var viewContext = html.ViewContext; var isChildAction = viewContext.Controller.ControllerContext.IsChildAction; if (isChildAction) viewContext = html.ViewContext.ParentActionViewContext; var routeValues = viewContext.RouteData.Values; var currentAction = routeValues["action"].ToString(); var currentController = routeValues["controller"].ToString(); var acceptedActions = actions.Trim().Split(',').Distinct().ToArray(); var acceptedControllers = controllers.Trim().Split(',').Distinct().ToArray(); return (acceptedActions.Contains(currentAction) && acceptedControllers.Contains(currentController)) ? cssClass : ""; }
用法:
<ul> <li class="@Html.IsSelected(actions: "Home", controllers: "Default")"> <a href="@Url.Action("Home", "Default")">Home</a> </li> <li class="@Html.IsSelected(actions: "List,Detail", controllers: "Default")"> <a href="@Url.Action("List", "Default")">List</a> </li> </ul>
以上是如何高效地将'Active”类添加到 ASP.NET MVC 的 Html.ActionLink 以进行 Bootstrap 导航?的详细内容。更多信息请关注PHP中文网其他相关文章!