【问题标题】:ASP.net MVC - Navigation and highlighting the "current" linkASP.net MVC - 导航和突出显示“当前”链接
【发布时间】:2010-11-04 17:52:16
【问题描述】:

当您创建一个新的 MVC 项目时,它会创建一个带有以下标记的 Site.master:

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

如果我在该页面上,我想在此处放置代码以突出显示当前链接。

如果我添加另一个链接,例如:

<li><%: Html.ActionLink("Products", "Index", "Products")%></li>

如果我在 Products 控制器中执行任何操作,我希望 Products 链接处于活动状态(使用 .active 之类的 css 类)。

如果我在 HomeController About 操作中,About 链接应该处于活动状态。如果我在 HomeController 的 Index 操作中,Home 链接应该是活动的。

在 MVC 中执行此操作的最佳方法是什么?

【问题讨论】:

    标签: c# asp.net-mvc navigation


    【解决方案1】:

    查看this blog post

    它展示了如何创建一个您调用的 HTML 扩展,而不是通常的 Html.ActionLink 该扩展然后将 class="selected" 附加到当前活动的列表项。

    然后,您可以在 CSS 中添加任何您想要的格式/突出显示

    编辑

    只是添加一些代码而不仅仅是一个链接。

    public static class HtmlHelpers
    {
    
        public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper,
                                            string linkText,
                                            string actionName,
                                            string controllerName
                                            )
        {
    
            string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
            string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
    
            if (actionName == currentAction && controllerName == currentController)
            {
                return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "selected" });
            }
    
            return htmlHelper.ActionLink(linkText, actionName, controllerName);
    
    
        }
    } 
    

    现在您需要在 CSS 中定义 selected 类,然后在您的视图中在顶部添加 using 语句。

    @using ProjectNamespace.HtmlHelpers

    并使用MenuLink 而不是ActionLink

    @Html.MenuLink("Your Menu Item", "Action", "Controller")

    【讨论】:

    • 注意:ActionLink其实本身就是一个扩展方法,一定要包含使用System.Web.Mvc.Html;在您的代码文件中,否则 Visual Studio 将无法找到它。
    • 使用 JetBrains.Annotations nuget 包在 Razor 视图中突出显示控制器和操作。 [AspMvcController][AspMvcAction].
    【解决方案2】:

    您可以通过使用“data-”属性来识别容器,然后使用 jQuery 更改链接的 CSS 类来做到这一点,如下所示:

    <div class="..." data-navigation="true">
                        <ul class="...">
                            <li>@Html.ActionLink("About", "About", "Home")</li>
                            <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                        </ul>
    </div>
    
    <script>
        $(function () {
            $("div[data-navigation='true']").find("li").children("a").each(function () {
                if ($(this).attr("href") === window.location.pathname) {
                    $(this).parent().addClass("active");
                }
            });
        });
    </script>
    

    【讨论】:

    • 导航栏中的下拉列表怎么样,似乎不起作用
    【解决方案3】:

    这是一种将其实现为 MVC 助手的方法:

    @helper NavigationLink(string linkText, string actionName, string controllerName)
    {
        if(ViewContext.RouteData.GetRequiredString("action").Equals(actionName, StringComparison.OrdinalIgnoreCase) &&
           ViewContext.RouteData.GetRequiredString("controller").Equals(controllerName, StringComparison.OrdinalIgnoreCase))
        {
            <span>@linkText</span>
        }
        else
        {
            @Html.ActionLink(linkText, actionName, controllerName);
        }
    }
    

    然后可以像下面这样使用它:

    @NavigationLink("Home", "index", "home")
    @NavigationLink("About Us", "about", "home")
    

    一篇关于 MVC 助手的好文章可以在这里找到:http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

    【讨论】:

      【解决方案4】:

      我用这个方法和一个 htmlhelper 来解决这个问题:

      public static class HtmlHelpers
      {
          public static MvcHtmlString MenuLink(this HtmlHelper htmlHelper,
                                                  string linkText,
                                                  string actionName,
                                                  string controllerName
                                              )
          {
      
              string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
              string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
      
              if (actionName.Equals(currentAction, StringComparison.InvariantCultureIgnoreCase) && controllerName.Equals(currentController, StringComparison.InvariantCultureIgnoreCase))
              {
                  return htmlHelper.ActionLink(linkText, actionName, controllerName, null, new { @class = "active" });
              }
      
              return htmlHelper.ActionLink(linkText, actionName, controllerName);
      
          }
      }
      

      为了视图

      @Html.MenuLink"Linktext", "action", "controller")
      

      【讨论】:

        【解决方案5】:

        您可能想查看我的一系列 MVC 导航控件,其中包括自动突出显示当前链接的功能:

        http://mvcquicknav.apphb.com/

        【讨论】:

          【解决方案6】:

          感谢@codingbadger 的解决方案。

          我必须在多个操作上突出显示我的导航链接,因此我决定添加更多包含控制器-操作对的参数,如果访问其中任何一个组合,它也会突出显示链接。而且,就我而言,突出显示类将应用于&lt;li&gt; 元素。

          我将我的代码放在这里,希望它对将来的人有所帮助:

          • 这里是辅助方法:

            /// <summary>
            /// The link will be highlighted when it is used to redirect and also be highlighted when any action-controller pair is used specified in the otherActions parameter.
            /// </summary>
            /// <param name="selectedClass">The CSS class that will be applied to the selected link</param>
            /// <param name="otherActions">A list of tuples containing pairs of Action Name and Controller Name respectively</param>
            public static MvcHtmlString NavLink(this HtmlHelper htmlHelper, string linkText, string actionName, string controllerName, string parentElement, string selectedClass, IEnumerable<Tuple<string, string>> otherActions)
            {
                string currentAction = htmlHelper.ViewContext.RouteData.GetRequiredString("action");
                string currentController = htmlHelper.ViewContext.RouteData.GetRequiredString("controller");
            
                if ((actionName == currentAction && controllerName == currentController) || 
                    (otherActions != null && otherActions.Any(pair => pair.Item1 == currentAction && pair.Item2 == currentController)))
                {
                    return new MvcHtmlString($"<{parentElement} class=\"{selectedClass}\">{htmlHelper.ActionLink(linkText, actionName, controllerName)}</{parentElement}>");
                }
            
                return new MvcHtmlString($"<{parentElement}>{htmlHelper.ActionLink(linkText, actionName, controllerName)}</{parentElement}>");
            }
            
          • 还有,这是一个如何使用它的示例:

          <ul>
            @Html.NavLink("Check your eligibility", "CheckEligibility", "Eligibility", "li", "current-page", new Tuple<string, string>[]
             {
                 new Tuple<string, string>("Index", "Eligibility"),
                 new Tuple<string, string>("RecheckEligibility", "Eligibility")
             })
             @Html.NavLink("Apply for my loan", "Apply", "Loan", "li", "current-page")
          </ul>

          【讨论】:

            【解决方案7】:

            首先制作一个 Helper 类和 HTML Helper 方法

             public static string IsActive(this HtmlHelper html,string control,string action)
                {
                    var routeData = html.ViewContext.RouteData;
            
                    var routeAction = (string)routeData.Values["action"];
                    var routeControl = (string)routeData.Values["controller"];
            
                    // both must match
                    var returnActive = control == routeControl &&
                                       action == routeAction;
            
                    return returnActive ? "active" : "";
                }
            

            在 View 或 Layour 部分中,只需使用适当的控制器和操作调用 Helper 方法。

              @using YourNamespace.HtmlHelpermethodName
            
             <a class="nav-link @Html.IsActive("Dashboard","Index")" href="@Url.Action("Index","Dashboard")">
            

            这将在类属性中添加“活动”字符串,它会显示为

             <a class="nav-link active" href="@Url.Action("Index","Dashboard")">
            

            【讨论】:

              【解决方案8】:
              public ActionResult SignIn(User user)
              {
                  User u = db.Users.Where(p=>p.Email == user.Email & p.Password == user.Password).FirstOrDefault();
                  if (u == null)
                  {
                     return View();
                  }
                  var id = u.Id;
                  Session["id_user"] = id;
              
                  return RedirectToAction("Index", "Home");
              }
              

              【讨论】:

                【解决方案9】:
                <div class="navbar-collapse collapse">
                            <ul class="nav navbar-nav">
                                <li>@Html.ActionLink("Home", "Index", "Home")</li>
                                <li>@Html.ActionLink("About", "About", "Home")</li>
                                <li>@Html.ActionLink("Contact", "Contact", "Home")</li>
                                <li>@Html.ActionLink("Products", "Index", "Products")</li>
                                <li class="dropdown">
                                    <a href="#" class="dropdown-toggle" data-toggle="dropdown">Archivo<b class="caret"></b></a>
                                    <ul class="dropdown-menu">
                                        <li>@Html.ActionLink("Document Type", "Index", "DocumentTypes")</li>
                                        <li>@Html.ActionLink("Employee", "Index", "Employees")</li>
                                        <li>@Html.ActionLink("Suppliers", "Index", "Suppliers")</li>
                                    </ul>
                                </li>    
                            </ul>
                            @Html.Partial("_LoginPartial")
                        </div>
                

                【讨论】:

                  猜你喜欢
                  • 2015-04-02
                  • 2016-10-01
                  • 1970-01-01
                  • 2015-08-23
                  • 2011-04-08
                  • 1970-01-01
                  • 2011-11-24
                  • 1970-01-01
                  相关资源
                  最近更新 更多