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# 6.0 and the .NET 4.6 Framework
    C# 6.0 and the .NET 4.6 Framework
    More InfoMicrosoft Visual C# Step by Step (8th Edition) (Developer Reference)
    Microsoft Visual C# Step by Step (8th Edition) (Developer Reference)
    More InfoThe C# Player's Guide (3rd Edition)
    The C# Player's Guide (3rd Edition)
    More InfoThe C# Player's Guide (2nd Edition)
    The C# Player's Guide (2nd Edition)
    More InfoC# 6.0 in a Nutshell: The Definitive Reference
    C# 6.0 in a Nutshell: The Definitive Reference
    More InfoC# Programming: The No-Nonsense Guide: Learn C# Programming Within 12 Hours! (Including A Free C# Cheatsheet & 30+ Exercises)
    C# Programming: The No-Nonsense Guide: Learn C# Programming Within 12 Hours! (Including A Free C# Cheatsheet & 30+ Exercises)
    More InfoC#: C# Crash Course - The Complete Beginner's Course to Learn C# Programming in 15 Clear-Cut Lessons - Including Dozens of Practical Examples & Exercises (C# Series)
    C#: C# Crash Course - The Complete Beginner's Course to Learn C# Programming in 15 Clear-Cut Lessons - Including Dozens of Practical Examples & Exercises (C# Series)