如何在 ASP.NET MVC 中直观地指示当前页面?

发布于 2024-08-05 05:18:34 字数 771 浏览 5 评论 0原文

作为讨论的基础。创建标准 ASP.NET MVC Web 项目。

它将在母版页中包含两个菜单项:

<div id="menucontainer">
  <ul id="menu">
    <li>
      <%= Html.ActionLink("Home", "Index", "Home")%></li>
    <li>
      <%= Html.ActionLink("About", "About", "Home")%></li>
  </ul>
</div>

如何设置指示当前页面的视觉 CSS 样式。 例如,当在“关于”页面/控制器中时,我本质上想这样做:

<%= Html.ActionLink("About", "About", "Home", new {class="current"})%></li>

当然,当在主页上时:(

<%= Html.ActionLink("Home", "Index", "Home", new {class="current"})%></li>

有一个 CSS 样式名称 current,在菜单中直观地指示这是当前页面。 )

我可以将菜单 div 从母版页分解为内容占位符,但这意味着我必须将菜单放在每个页面上。

任何想法,有一个好的解决方案吗?

As a base for discussion. Create a standard ASP.NET MVC Web project.

It will contain two menu items in the master page:

<div id="menucontainer">
  <ul id="menu">
    <li>
      <%= Html.ActionLink("Home", "Index", "Home")%></li>
    <li>
      <%= Html.ActionLink("About", "About", "Home")%></li>
  </ul>
</div>

How can I set the visual CSS style indicating the current page.
For example, when in the About page/controller, I essentially would like to do this:

<%= Html.ActionLink("About", "About", "Home", new {class="current"})%></li>

And, of course, when on the home page:

<%= Html.ActionLink("Home", "Index", "Home", new {class="current"})%></li>

(Having a CSS style names current that visually indicates in the menu that this is the current page.)

I could break out the menu div from the master page into a content place holder, but that would mean that I must put the menu on every page.

Any ideas, is there a nice solution to this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

灼痛 2024-08-12 05:18:34

最简单的方法是从 ViewContext 的 RouteData 获取当前控制器和操作。请注意签名的更改以及使用 @ 来转义关键字。

<% var controller = ViewContext.RouteData.Values["controller"] as string ?? "Home";
   var action = ViewContext.RouteData.Values["action"] as string ?? "Index";
   var page = (controller + ":" + action).ToLower();
 %>

<%= Html.ActionLink( "About", "About", "Home", null,
                     new { @class = page == "home:about" ? "current" : "" ) %>
<%= Html.ActionLink( "Home", "Index", "Home", null,
                     new { @class = page == "home:index" ? "current" : "" ) %>

请注意,您可以将其与 @Jon 之类的 HtmlHelper 扩展结合起来,并使其更清晰。

<%= Html.MenuLink( "About", "About", "Home", null, null, "current" ) %>

MenuActionLink 在哪里

public static class MenuHelperExtensions
{
     public static string MenuLink( this HtmlHelper helper,
                                    string text,
                                    string action,
                                    string controller,
                                    object routeValues,
                                    object htmlAttributes,
                                    string currentClass )
     {
         RouteValueDictionary attributes = new RouteValueDictionary( htmlAttributes );
         string currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
         string currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";
         string page = string.Format( "{0}:{1}", currentController, currentAction ).ToLower();
         string thisPage = string.Format( "{0}:{1}", controller, action ).ToLower();
         attributes["class"] = (page == thisPage) ? currentClass : "";
        return helper.ActionLink( text, action, controller, new RouteValueDictionary( routeValues ), attributes );
     }
}

The easiest way is to get the current controller and action from the ViewContext's RouteData. Note the change in signature and use of @ to escape the keyword.

<% var controller = ViewContext.RouteData.Values["controller"] as string ?? "Home";
   var action = ViewContext.RouteData.Values["action"] as string ?? "Index";
   var page = (controller + ":" + action).ToLower();
 %>

<%= Html.ActionLink( "About", "About", "Home", null,
                     new { @class = page == "home:about" ? "current" : "" ) %>
<%= Html.ActionLink( "Home", "Index", "Home", null,
                     new { @class = page == "home:index" ? "current" : "" ) %>

Note that you could combine this an HtmlHelper extension like @Jon's and make it cleaner.

<%= Html.MenuLink( "About", "About", "Home", null, null, "current" ) %>

Where MenuActionLink is

public static class MenuHelperExtensions
{
     public static string MenuLink( this HtmlHelper helper,
                                    string text,
                                    string action,
                                    string controller,
                                    object routeValues,
                                    object htmlAttributes,
                                    string currentClass )
     {
         RouteValueDictionary attributes = new RouteValueDictionary( htmlAttributes );
         string currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
         string currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";
         string page = string.Format( "{0}:{1}", currentController, currentAction ).ToLower();
         string thisPage = string.Format( "{0}:{1}", controller, action ).ToLower();
         attributes["class"] = (page == thisPage) ? currentClass : "";
        return helper.ActionLink( text, action, controller, new RouteValueDictionary( routeValues ), attributes );
     }
}
顾北清歌寒 2024-08-12 05:18:34

我最近为此创建了一个 HTML Helper,如下所示:

public static string NavigationLink(this HtmlHelper helper, string path, string text)
{
    string cssClass = String.Empty;
    if (HttpContext.Current.Request.Path.IndexOf(path) != -1)
    {
        cssClass = "class = 'selected'";
    }

    return String.Format(@"<li><a href='{0}' {1}>{2}</a></li>", path, cssClass, text);
}

实现如下所示:

  <ul id="Navigation">
  <%=Html.NavigationLink("/Path1", "Text1")%>
  <%=Html.NavigationLink("/Path2", "Text2")%>
  <%=Html.NavigationLink("/Path3", "Text3")%>
  <%=Html.NavigationLink("/Path4", "Text4")%>
  </ul>

I recently created an HTML Helper for this that looks like:

public static string NavigationLink(this HtmlHelper helper, string path, string text)
{
    string cssClass = String.Empty;
    if (HttpContext.Current.Request.Path.IndexOf(path) != -1)
    {
        cssClass = "class = 'selected'";
    }

    return String.Format(@"<li><a href='{0}' {1}>{2}</a></li>", path, cssClass, text);
}

The Implementation looks like this:

  <ul id="Navigation">
  <%=Html.NavigationLink("/Path1", "Text1")%>
  <%=Html.NavigationLink("/Path2", "Text2")%>
  <%=Html.NavigationLink("/Path3", "Text3")%>
  <%=Html.NavigationLink("/Path4", "Text4")%>
  </ul>
假装爱人 2024-08-12 05:18:34

如果您使用 T4MVC,则可以使用:

        public static HtmlString MenuLink(
        this HtmlHelper helper,
        string text,
        IT4MVCActionResult action,
        object htmlAttributes = null)
    {
        var currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
        var currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";

        var attributes = new RouteValueDictionary(htmlAttributes);
        var cssClass = (attributes.ContainsKey("class"))
                           ? attributes["class"] + " "
                           : string.Empty;

        string selectedClass;
        if(action.Controller.Equals(currentController, StringComparison.InvariantCultureIgnoreCase)
        {
            selectedClass = "selected-parent";
            if(action.Action.Equals(currentAction, StringComparison.InvariantCultureIgnoreCase))
                selectedClass = "selected";
        }
        cssClass += selectedClass;

        attributes["class"] = cssClass;

        return helper.ActionLink(text, (ActionResult)action, attributes);
    }

If you are using T4MVC, you can use this:

        public static HtmlString MenuLink(
        this HtmlHelper helper,
        string text,
        IT4MVCActionResult action,
        object htmlAttributes = null)
    {
        var currentController = helper.ViewContext.RouteData.Values["controller"] as string ?? "home";
        var currentAction = helper.ViewContext.RouteData.Values["action"] as string ?? "index";

        var attributes = new RouteValueDictionary(htmlAttributes);
        var cssClass = (attributes.ContainsKey("class"))
                           ? attributes["class"] + " "
                           : string.Empty;

        string selectedClass;
        if(action.Controller.Equals(currentController, StringComparison.InvariantCultureIgnoreCase)
        {
            selectedClass = "selected-parent";
            if(action.Action.Equals(currentAction, StringComparison.InvariantCultureIgnoreCase))
                selectedClass = "selected";
        }
        cssClass += selectedClass;

        attributes["class"] = cssClass;

        return helper.ActionLink(text, (ActionResult)action, attributes);
    }
三月梨花 2024-08-12 05:18:34

它可能只是第 5 个参数,因此在 html 属性之前插入一个 null。这篇文章在这里描述了它,尽管你可以在第四个参数中传递一些东西,第五个参数是专门针对 HTMLattributes 的

It might just be that it's the 5th parameter, so slot a null before your html attribute. This post here describes it as such, though you can pass in some stuff on the 4th arguement, the 5th is specifically for HTMLattributes

断舍离 2024-08-12 05:18:34
<script type="javascript/text">
$( document ).ready( function() {

        @if (Request.Url.AbsolutePath.ToLower() == "/") 
        {
            @Html.Raw("$('.navbar-nav li').eq(0).attr('class','active');")
        }

        @if (Request.Url.AbsolutePath.ToLower().Contains("details")) 
        {
            @Html.Raw("$('.navbar-nav li').eq(1).attr('class','active');")
        }

        @if (Request.Url.AbsolutePath.ToLower().Contains("schedule")) 
        {
            @Html.Raw("$('.navbar-nav li').eq(2).attr('class','active');")
        }

    });
</script>

在 5 分钟内将其整合在一起,我可能可以重构它,但应该给你基本的想法,它可能对较小的网站最有用。

<script type="javascript/text">
$( document ).ready( function() {

        @if (Request.Url.AbsolutePath.ToLower() == "/") 
        {
            @Html.Raw("$('.navbar-nav li').eq(0).attr('class','active');")
        }

        @if (Request.Url.AbsolutePath.ToLower().Contains("details")) 
        {
            @Html.Raw("$('.navbar-nav li').eq(1).attr('class','active');")
        }

        @if (Request.Url.AbsolutePath.ToLower().Contains("schedule")) 
        {
            @Html.Raw("$('.navbar-nav li').eq(2).attr('class','active');")
        }

    });
</script>

Chucked this together in 5mins, I could probably refactor it, but should give you the basic idea, its probably most useful for smaller sites.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文