ASP.NET MVC - 当前页突出导航 [英] ASP.NET MVC - Current Page highlighting in navigation
问题描述
我不知道这怎么可能使用ASP.NET MVC 3,当一个CSS类添加到当前页面中您的导航?这里是我的导航在我的_Layout.cshtml文件:
I'm wondering how is it possible to add a CSS Class to the current page in your navigation when using ASP.NET MVC 3? Here is my navigation in my _Layout.cshtml file:
<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>
正如你可以看到我在与具有CSS类当前适用于它的第一个导航4链接,我希望能够添加/删除取决于这个类在我的导航中的各个链接在其上页面的用户是在。这可能吗?
As you can see I have 4 links in my navigation with the first one having the CSS class "current" applied to it, I'd like to be able to add/remove this class to the different links in my navigation depending on which page the user is at. Is this possible?
干杯
推荐答案
我会建议使用此扩展方法。是这样的:
I would recommend using an extension method for this. Something like:
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);
}
然后就可以通过包括扩展的空间,只是调用你的方法用它在你的观点:
Then you can use it in your View by including the namespace of your extension and just calling your method:
@using MyExtensionNamespace;
...
@Html.NavigationLink("Product Search", "Index", "Home")
| @Html.NavigationLink("Orders", "Index", "Orders")
| @Html.NavigationLink("My Account", "MyAccount", "Account")
| @Html.NavigationLink("Logout", "LogOff", "Account")
这有让您的剃须刀干净了一点的好处,并在其他视图轻松地重用。
This has the benefit of keeping your razor a little cleaner and is easily reusable in other views.
这篇关于ASP.NET MVC - 当前页突出导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!