I have seen this done a few different ways, but not specifically what I am looking for. I currently have a custom HtmlHelper that adds “class=’currentPage'” to an ActionLink to highlight the current page in a navigation system.
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
string text,
string action,
string controller
)
{
string value;
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
{
value = htmlHelper.ActionLink(text, action, new { controller = controller }, new { @class = "currentPage" }).ToHtmlString();
return MvcHtmlString.Create(value.ToString());
}
value = htmlHelper.ActionLink(text, action, controller).ToHtmlString();
return MvcHtmlString.Create(value.ToString());
}
This works wonderfully, but I have an admin area where I also have an image associated with each menu item. The image is located within the link like so:
<li><a href="/Admin/Blog"><img src="/Content/images/icons/page_edit.png" alt="" /> Blog</a></li>
I want to create an override method for “MenuItem” that adds the image inside the ActionLink, but I am a bit stumped. Currently I have the following, which puts the img tag on the outside…
public static MvcHtmlString MenuItem(
this HtmlHelper htmlHelper,
bool isAdmin,
string text,
string action,
string controller
)
{
string value;
var routeData = htmlHelper.ViewContext.RouteData;
var currentAction = routeData.GetRequiredString("action");
var currentController = routeData.GetRequiredString("controller");
value = "<img src='/Content/images/admin_icons/" + text + ".png' alt='' /> ";
if (string.Equals(currentAction, action, StringComparison.OrdinalIgnoreCase) &&
string.Equals(currentController, controller, StringComparison.OrdinalIgnoreCase))
{
value += htmlHelper.ActionLink(text, action, new { controller = controller }, new { @class = "currentPage" }).ToHtmlString();
}
else
{
value += htmlHelper.ActionLink(text, action, controller).ToHtmlString();
}
return MvcHtmlString.Create(value.ToString());
}
Any ideas?
I would generate the URL using UrlHelper, and then format the string. My example does not deal with adding the conditional class, but that should be easy to include.