ASP.net MVC - Navigation and highlighting the “current” link

前端 未结 9 1641
清酒与你
清酒与你 2020-12-30 11:10

When you create a new MVC project it creates a Site.master with the following markup:

    <
9条回答
  •  滥情空心
    2020-12-30 11:24

    Check out this blog post

    It shows how to create an HTML Extension that you call instead of the usual Html.ActionLink The extension then appends class="selected" to the list item that is currently active.

    You can then put whatever formatting/highlighting you want in your CSS

    EDIT

    Just adding some code to rather than just a link.

    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);
    
    
        }
    } 
    

    Now you need to define your selected class in your CSS and then in your views add a using statement at the top.

    @using ProjectNamespace.HtmlHelpers

    And use the MenuLink instead of ActionLink

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

提交回复
热议问题