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

前端 未结 9 1614
清酒与你
清酒与你 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:21

    Here is a way to implement this as an MVC helper:

    @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))
        {
            @linkText
        }
        else
        {
            @Html.ActionLink(linkText, actionName, controllerName);
        }
    }
    

    It can then be used similar to the following:

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

    A good article on MVC helpers can be found here: http://weblogs.asp.net/scottgu/archive/2011/05/12/asp-net-mvc-3-and-the-helper-syntax-within-razor.aspx

提交回复
热议问题