Skip to content

Instantly share code, notes, and snippets.

@timiles
Created June 1, 2012 12:13
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save timiles/2851684 to your computer and use it in GitHub Desktop.
MenuActionLink HtmlHelper Extensions
/// <summary>
/// adds the active class if the link's action & controller matches current request
/// </summary>
public static MvcHtmlString MenuActionLink(this HtmlHelper htmlHelper,
string linkText, string actionName, string controllerName,
object routeValues = null, object htmlAttributes = null,
string activeClassName = "active")
{
IDictionary<string, object> htmlAttributesDictionary =
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (((string)htmlHelper.ViewContext.RouteData.Values["controller"])
.Equals(controllerName, StringComparison.OrdinalIgnoreCase) &&
((string)htmlHelper.ViewContext.RouteData.Values["action"])
.Equals(actionName, StringComparison.OrdinalIgnoreCase))
{
// careful in case class already exists
htmlAttributesDictionary["class"] += " " + activeClassName;
}
return htmlHelper.ActionLink(linkText, actionName, controllerName,
new RouteValueDictionary(routeValues),
htmlAttributesDictionary);
}
/// <summary>
/// adds the active class if the link's path matches current request
/// </summary>
public static MvcHtmlString MenuActionLink(this HtmlHelper htmlHelper,
string linkText, string path, object htmlAttributes = null,
string activeClassName = "active")
{
IDictionary<string, object> htmlAttributesDictionary =
HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
if (HttpContext.Current.Request.Path
.Equals(path, StringComparison.OrdinalIgnoreCase))
{
// careful in case class already exists
htmlAttributesDictionary["class"] += " " + activeClassName;
}
var tagBuilder = new TagBuilder("a")
{
InnerHtml = !string.IsNullOrEmpty(linkText)
? HttpUtility.HtmlEncode(linkText)
: string.Empty
};
tagBuilder.MergeAttributes(htmlAttributesDictionary);
tagBuilder.MergeAttribute("href", path);
return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment