Asp.net-Mvc-3

ASP.NET MVC - 目前頁面在導航中突出顯示

  • January 29, 2022

我想知道在使用 ASP.NET MVC 3 時如何將 CSS 類添加到導航中的目前頁面?這是我在 _Layout.cshtml 文件中的導航:

<p>@Html.ActionLink("Product Search", "Index", new { controller = "Home" }, new { @class = "current" })
               | @Html.ActionLink("Orders", "Index", new { controller = "Orders" }) 
               | @Html.ActionLink("My Account", "MyAccount", new { controller = "Account" })
               | @Html.ActionLink("Logout", "LogOff", new { controller = "Account" })</p>

如您所見,我的導航中有 4 個連結,第一個連結應用了 CSS 類“目前”,我希望能夠根據哪個頁面將此類添加/刪除到導航中的不同連結使用者在。這可能嗎?

乾杯

我建議為此使用擴展方法。就像是:

public static HtmlString NavigationLink(
   this HtmlHelper html,
   string linkText,
   string actionName,
   string controllerName)
{
   string contextAction = (string)html.ViewContext.RouteData.Values["action"];
   string contextController = (string)html.ViewContext.RouteData.Values["controller"];

   bool isCurrent =
       string.Equals(contextAction, actionName, StringComparison.CurrentCultureIgnoreCase) &&
       string.Equals(contextController, controllerName, StringComparison.CurrentCultureIgnoreCase);

   return html.ActionLink(
       linkText,
       actionName,
       controllerName,
       routeValues: null,
       htmlAttributes: isCurrent ? new { @class = "current" } : null);
}

然後你可以在你的視圖中使用它,方法是包含擴展的命名空間並呼叫你的方法:

@using MyExtensionNamespace;

...

 @Html.NavigationLink("Product Search", "Index", "Home")
| @Html.NavigationLink("Orders", "Index", "Orders") 
| @Html.NavigationLink("My Account", "MyAccount", "Account")
| @Html.NavigationLink("Logout", "LogOff", "Account")

這樣做的好處是讓你的剃須刀更乾淨一些,並且可以在其他視圖中輕鬆重複使用。

你可以這樣做

@{ 
  var currentController = ViewContext.RouteData.Values["controller"] as string ?? "Home";
  var currentAction = ViewContext.RouteData.Values["action"] as string ?? "Index";
  var currentPage = (currentController + "-" + currentAction ).ToLower();
}

@Html.ActionLink("Product Search", "Index", "Home", null,
                new { @class = currentPage == "home-index" ? "current" : "" })
@Html.ActionLink("MyAccount", "MyAccount", "Account", null,
                 new { @class = currentPage == "account-myaccount" ? "current" : "" })

引用自:https://stackoverflow.com/questions/9289909