MenuActionLink HtmlHelper Extensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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