views:

173

answers:

1

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

A: 

Names aren't attributes of routes directly; they're just a way for the collection to map strings to routes. So you can't get the route name from the current route.

But you can compare the routes themselves rather than using the name. Since you have the current RouteBase instance (you can get it via HtmlHelper.ViewContext.RouteData.Route) and the RouteCollection (via HtmlHelper.RouteCollection), you can use RouteCollection.Item to get the RouteBase corresponding to the target route name. The compare the returned RouteBase instance with the current RouteBase instance.

Levi