在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中文網其他相關文章!