asp.net-mvc-3 – ASP.NET MVC – 导航当前页面突出显示

前端之家收集整理的这篇文章主要介绍了asp.net-mvc-3 – ASP.NET MVC – 导航当前页面突出显示前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道当使用ASP.NET MVC 3时,如何在导航中的当前页面添加一个CSS类?这是我在_Layout.cshtml文件中的导航: @H_301_2@<p>@Html.ActionLink("Product Search","Index",new { controller = "Home" },new { @class = "current" }) | @Html.ActionLink("Orders",new { controller = "Orders" }) | @Html.ActionLink("My Account","MyAccount",new { controller = "Account" }) | @Html.ActionLink("logout","logoff",new { controller = "Account" })</p>

正如你可以看到,我的导航中有4个链接,第一个CSS类“当前”应用于它,我希望能够添加/删除这个类到我的导航中的不同链接取决于哪个页面用户在.这可能吗?

干杯

解决方法

我建议使用扩展方法.就像是: @H_301_2@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,routeValues: null,htmlAttributes: isCurrent ? new { @class = "current" } : null); }

然后,您可以通过添加扩展名的命名空间并调用方法在View中使用它:

@H_301_2@@using MyExtensionNamespace; ... @Html.NavigationLink("Product Search","Home") | @Html.NavigationLink("Orders","Orders") | @Html.NavigationLink("My Account","Account") | @Html.NavigationLink("logout","Account")

这样做有利于保持剃须刀更清洁,并且在其他视图中容易重复使用.

猜你在找的asp.Net相关文章