0

Using bootstrap I ran into the problem of having to set the active class on certain links. I found this helper method out on the interwebs and was adding some functionality to it. Basically I wanted to add RouteValueDictionary and Html items to it. For some reason, my view is passing a null RouteValueDictionary instead of the values I'm populating.

I think my problem is I am missing something on the view side, the HTML rendered might not actually produce a route value the way it should.

Extension method:

public static MvcHtmlString MenuLink(this HtmlHelper pHtmlHelper, string pLinkText, string pActionName, string pControllerName, RouteValueDictionary pRouteValues)
{
    var vCurrentAction = pHtmlHelper.ViewContext.RouteData.GetRequiredString("action");
    var vCurrentController = pHtmlHelper.ViewContext.RouteData.GetRequiredString("controller");
    var vBuilder = new TagBuilder("li") { InnerHtml = pHtmlHelper.ActionLink(pLinkText, pActionName, pControllerName, pRouteValues, null).ToHtmlString() };

    if (pControllerName == vCurrentController && pActionName == vCurrentAction) vBuilder.AddCssClass("active");

    return new MvcHtmlString(vBuilder.ToString());
}

View (portion):

@Html.MenuLink("Account", "Details", "Dashboard", new RouteValueDictionary(new {id="Account"}))

Rendered HTML:

<a href="/Dashboard/Details/Account">Account</a>

So again, the problem I'm having is MenuLink gets a null RouteValueDictionary, I feel like it should contain id!

(Note... pHtmlHelper.ViewContext.RouteData actually contains the id tag in it's RouteData Values....)

danludwig
  • 46,965
  • 25
  • 159
  • 237
Tada
  • 1,585
  • 2
  • 16
  • 26

1 Answers1

0

Your code is working as expected assuming you have a route that looks like (depending on the order of the routes):

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters*
    new { controller = "Home", action = "Index", 
    id = UrlParameter.Optional }
);

So the code:

 pHtmlHelper.ActionLink(
   pLinkText,       // Link Text 
   pActionName,     // Action
   pControllerName, // Controller
   pRouteValues,    // Route Values
   null)
   .ToHtmlString() };

The Url would be

/Dashboard/Details/{id}

Route Values:

 {
   id="Account"
 }

becomes:

/Dashboard/Details/Account
Erik Philips
  • 53,428
  • 11
  • 128
  • 150