加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-15 23:35:41 所属栏目:asp.Net 来源:网络整理
导读:我想知道当使用ASP.NET MVC 3时,如何在导航中的当前页面中添加一个CSS类?这是我在_Layout.cshtml文件中的导航: p@Html.ActionLink("Product Search","Index",new { controller = "Home" },new { @class = "current" }) | @Html.ActionLink("Orders",new {
我想知道当使用ASP.NET MVC 3时,如何在导航中的当前页面中添加一个CSS类?这是我在_Layout.cshtml文件中的导航:
<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类“当前”应用于它,我希望能够添加/删除这个类到我的导航中的不同链接取决于哪个页面用户在.这可能吗?

干杯

解决方法

我建议使用扩展方法.就像是:
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中使用它:

@using MyExtensionNamespace;

...

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读