Highlighting the Current Link in a Menu with ASP.NET MVC

C#
Copy to clipboard
fablecode
  1. // Source: http://trycatchfail.com/blog/post/Highlighting-the-Current-Link-in-a-Menu-with-ASPNET-MVC.aspx
  2.  
  3. public static MvcHtmlString MenuLink<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string linkText) where TController : Controller
  4. {
  5.     var linkRoute = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression(action);
  6.  
  7.     var currentRoute = helper.ViewContext.RouteData.Values;
  8.  
  9.     var actionLink = helper.ActionLink(action, linkText);
  10.  
  11.     var isCurrentRoute = linkRoute["controller"].ToString() == currentRoute["controller"].ToString() &&
  12.         linkRoute["action"].ToString() == currentRoute["action"].ToString();
  13.  
  14.     return MvcHtmlString.Create(string.Format("<li{0}>", isCurrentRoute ? " class=\"active\"" : string.Empty) + actionLink + "</li>");
  15. }
  16.  
  17. // Use
  18.  
  19. /*
  20.  
  21. <div class="nav-collapse collapse">
  22.     <ul class="nav">
  23.         @(Html.MenuLink<DashboardController>(c => c.Index(), "Dashboard"))
  24.         @(Html.MenuLink<TicketController>(c => c.Add(), "New Ticket"))
  25.     </ul>
  26.    ...
  27. </div>
  28.  
  29.  
  30. */

    Leave a comment

     
    Visual verification
     

    Related books

    More InfoLearn C# in One Day and Learn It Well: C# for Beginners with Hands-on Project (Learn Coding Fast with Hands-On Project) (Volume 3)
    Learn C# in One Day and Learn It Well: C# for Beginners with Hands-on Project (Learn Coding Fast with Hands-On Project) (Volume 3)
    More InfoC#: Programming Basics for Absolute Beginners (Step-By-Step C#) (Volume 1)
    C#: Programming Basics for Absolute Beginners (Step-By-Step C#) (Volume 1)
    More InfoC# Programming: THE NO-NONSENSE GUIDE: Learn C# Programming Within 12 Hours!
    C# Programming: THE NO-NONSENSE GUIDE: Learn C# Programming Within 12 Hours!
    More InfoThe C# Player's Guide (3rd Edition)
    The C# Player's Guide (3rd Edition)
    More InfoMicrosoft Visual C# Step by Step (8th Edition) (Developer Reference)
    Microsoft Visual C# Step by Step (8th Edition) (Developer Reference)
    More InfoThe C# Programming Yellow Book
    The C# Programming Yellow Book
    More InfoC# Programming in easy steps
    C# Programming in easy steps
    More InfoC# 6.0 and the .NET 4.6 Framework
    C# 6.0 and the .NET 4.6 Framework