Asp.Net Mvc highlighting current page link technique?

前端 未结 6 1155
误落风尘
误落风尘 2020-12-04 10:35

I need to highlight active link in the menu. My menu is in the master page by the way. I\'m looking for the best way to implement this? Any ideas?

相关标签:
6条回答
  • 2020-12-04 10:50

    I am always using this solution Html Part

    <ul>
       @Html.ListItemAction("Home Page","Index","Home")
       @Html.ListItemAction("Manage","Index","Home")
    </ul>
    

    Helper Part

     public static class ActiveLinkHelper
        { 
          public static MvcHtmlString ListItemAction(this HtmlHelper helper, string name, string actionName, string controllerName)
          {
            var currentControllerName = (string)helper.ViewContext.RouteData.Values["controller"];
            var currentActionName = (string)helper.ViewContext.RouteData.Values["action"];
            var sb = new StringBuilder();
            sb.AppendFormat("<li{0}", (currentControllerName.Equals(controllerName, StringComparison.CurrentCultureIgnoreCase) &&
                                                currentActionName.Equals(actionName, StringComparison.CurrentCultureIgnoreCase)
                                                    ? " class=\"active\">" : ">"));
            var url = new UrlHelper(HttpContext.Current.Request.RequestContext);
            sb.AppendFormat("<a href=\"{0}\">{1}</a>", url.Action(actionName, controllerName), name);
            sb.Append("</li>");
            return new MvcHtmlString(sb.ToString());
       }
    }
    
    0 讨论(0)
  • 2020-12-04 10:52

    The best way to handle this is to write an HTML helper. You could use RouteData.Values["action"] to get the currently executing action and compare to the menu name and if they match apply a CSS class that will highlight it.

    public static MvcHtmlString MenuItem(
        this HtmlHelper htmlHelper, 
        string action, 
        string text
    )
    {
        var menu = new TagBuilder("div");
        var currentAction = (string)htmlHelper.ViewContext.RouteData.Values["action"];
        if (string.Equals(
                currentAction, 
                action,
                StringComparison.CurrentCultureIgnoreCase)
        )
        {
            menu.AddCssClass("highlight");
        }
        menu.SetInnerText(text);
        return MvcHtmlString.Create(menu.ToString());
    }
    

    And then use this helper to render the menu items:

    <%: Html.MenuItem("about", "About us") %>
    <%: Html.MenuItem("contact", "Contact us") %>
    ...
    
    0 讨论(0)
  • 2020-12-04 10:53

    I use this solution:

    First - add attribute data-menuPageId to your menu links

    <ul class="menu">
       <li data-menuPageId="home">
                @(Html.Link<HomeController>(x => x.Index(), "Home"))
       </li>
       <li data-menuPageId="products">
                @(Html.Link<ProductsController>(x => x.Index(), "Products"))
       </li>
    </li>
    

    Next - add hidden field for current page Id to Layout.cshtml

    <input type="hidden" id="currentPageId" value="@(ViewBag.Page ?? "home")" />
    

    Add ViewBag.Page initializtion at your pages like Home or Products

    @{
        ViewBag.Page = "products";
    }
    

    And last thing you should reference this javascipt from yor Layout.cshtml

    $(function() {
        var pageIdAttr = "data-menuPageId";
        var currentPage = $("#currentPageId").attr("value");
    
        var menu = $(".menu");
    
        $("a[" + pageIdAttr + "]").removeClass("selected");
        $("a[" + pageIdAttr + "=\"" + currentPage + "\"]", menu).addClass("selected");
    });
    
    0 讨论(0)
  • 2020-12-04 10:58

    I'm pretty sure you can do this with pure CSS. It involves class selectors and faffing around with the body tag. I would go with the helper method every day of the week.

    0 讨论(0)
  • 2020-12-04 10:58

    The simplest solution:

    1) Connect jQuery to @RenderBody ()

    2) On Layout

    ...                        
    <li class="nav-item">
        <a class="nav-link text-dark" id="navItemPortfolio" asp-area="" asp-controller="Home" asp-action="Portfolio">Portfolio</a>
    </li>
    

    ...

    3) Write something similar on your page (View)

    <script>
        $(function () {
            $("#navItemPortfolio").addClass("active");
        });
    </script>
    
    0 讨论(0)
  • 2020-12-04 11:13

    In layout try like following:

    @{
        string url = Request.RawUrl;
    }
    @switch (url)
    {
        case "/home/":                
             @Html.ActionLink("Home", "../home/", null, new { @style = "background:#00bff3;" })
             @Html.ActionLink("Members", "../home/MembersList/")
        break;
        case "/home/MembersList/":
             @Html.ActionLink("Home", "../home/")
             @Html.ActionLink("Members", "../home/MembersList/", null, new { @style = "background:#00bff3;" })
        break;
        default:
                @Html.ActionLink("Home", "../home/")
                @Html.ActionLink("Members", "../home/MembersList/")
        break;
    }
    
    0 讨论(0)
提交回复
热议问题