HtmlHelper Getting the route name

Posted by Simon G on Stack Overflow See other posts from Stack Overflow or by Simon G
Published on 2010-04-01T18:23:08Z Indexed on 2010/04/01 23:33 UTC
Read the original article Hit count: 481

Filed under:
|
|
|

Hi,

I've created a html helper that adds a css class property to a li item if the user is on the current page. The helper looks like this:

public static string MenuItem( this HtmlHelper helper, string linkText, 
  string actionName, string controllerName, object routeValues, object htmlAttributes )
{
    string currentControllerName = 
     ( string )helper.ViewContext.RouteData.Values["controller"];
    string currentActionName = 
     ( string )helper.ViewContext.RouteData.Values["action"];

    var builder = new TagBuilder( "li" );

    // Add selected class
    if ( currentControllerName.Equals( controllerName, StringComparison.CurrentCultureIgnoreCase ) && 
          currentActionName.Equals( actionName, StringComparison.CurrentCultureIgnoreCase ) )
        builder.AddCssClass( "active" );

    // Add link
    builder.InnerHtml = helper.ActionLink( linkText, actionName, controllerName, routeValues, htmlAttributes );

    // Render Tag Builder
    return builder.ToString( TagRenderMode.Normal );
}

I want to expand this class so I can pass a route name to the helper and if the user is on that route then it adds the css class to the li item. However I'm having difficulty finding the route the user is on. Is this possible? The code I have so far is:

public static string MenuItem( this HtmlHelper helper, string linkText, string routeName, object routeValues, object htmlAttributes )
{
    string currentControllerName = 
      ( string )helper.ViewContext.RouteData.Values["controller"];
    string currentActionName = 
      ( string )helper.ViewContext.RouteData.Values["action"];

    var builder = new TagBuilder( "li" );

    // Add selected class
    // Some code for here
    // if ( routeName == currentRoute ) AddCssClass;

    // Add link
    builder.InnerHtml = helper.RouteLink( linkText, routeName, routeValues, htmlAttributes );

    // Render Tag Builder
    return builder.ToString( TagRenderMode.Normal );
}

BTW I'm using MVC 1.0.

Thanks

© Stack Overflow or respective owner

Related posts about asp.net-mvc

Related posts about routes