I have a custom helper class to highlight the selected menu item,
<li class="nav-item">
@Html.MenuLink("Contact000", "Contact", "Home", new { @class = "nav-link" })
</li>
I want to use the helper htmlattributes and append to CSS if selected condition is true. I have seen a Similiar question but was not able to find a question using
var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
Here is my code
public static MvcHtmlString MenuLink(this HtmlHelper helper, string text, string action, string controller, object htmlAttributes)
{
var routeData = helper.ViewContext.RouteData.Values;
var currentController = routeData["controller"];
var currentAction = routeData["action"];
var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (String.Equals(action, currentAction as string,
StringComparison.OrdinalIgnoreCase)
&&
String.Equals(controller, currentController as string,
StringComparison.OrdinalIgnoreCase))
{
if (attrs.ContainsKey("class"))
{
attrs["class"] += " " + "currentMenuItem";
}
return helper.ActionLink(text, action, controller, attrs);
}
return helper.ActionLink(text, action, controller, htmlAttributes);
}
using
var attrs = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
I can append to the attributes.
when I return the helper.actionlink the attrs is not parsed correctly, below is the html generated,
<li class="nav-item">
<a Count="1" Keys="System.Collections.Generic.Dictionary`2+KeyCollection[System.String,System.Object]" Values="System.Collections.Generic.Dictionary`2+ValueCollection[System.String,System.Object]" href="/Home/Contact?Length=4">Contact000</a>
</li>
I am trying to get the following,
<li class="nav-item">
<a class="nav-link currentMenuItem" href="/Home/Contact">Contact000</a>
</li>
How do I convert attrs back into htmlAttributes for the helper to work ?