Last active
May 28, 2018 20:30
-
-
Save cigano/6550e4f50a6750c2a50c to your computer and use it in GitHub Desktop.
My implementation of a ActionLink method Font-Awesome-Friendly.
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
<!-- language: c# --> | |
public static class HtmlExtensions | |
{ | |
public static IHtmlString FontAwesomeActionLink(this HtmlHelper htmlHelper, string linkText, | |
string actionName, string fontAwesomeClass, object routeValues = null, object htmlAttributes = null) | |
{ | |
return FontAwesomeActionLink(htmlHelper, linkText, actionName, null, fontAwesomeClass, routeValues, | |
htmlAttributes); | |
} | |
public static IHtmlString FontAwesomeActionLink(this HtmlHelper htmlHelper, string linkText, | |
string actionName, string controllerName, string fontAwesomeClass, object routeValues = null, object htmlAttributes = null) | |
{ | |
var targetUrl = UrlHelper.GenerateUrl(null, actionName, controllerName, ObjectToDictionary(routeValues), htmlHelper.RouteCollection, htmlHelper.ViewContext.RequestContext, true); | |
return new MvcHtmlString(GenerateLink(linkText, targetUrl, fontAwesomeClass, HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes))); | |
} | |
private static string GenerateLink(string linkText, | |
string targetUrl, | |
string fontAwesomeClass, | |
IDictionary<string, object> htmlAttributes | |
) | |
{ | |
var a = new TagBuilder("a"); | |
a.MergeAttributes(htmlAttributes); | |
a.MergeAttribute("href", targetUrl); | |
var i = new TagBuilder("i"); | |
i.MergeAttribute("class", "fa " + fontAwesomeClass); | |
a.InnerHtml = i.ToString(TagRenderMode.Normal) + " " + linkText; | |
return a.ToString(TagRenderMode.Normal); | |
} | |
public static RouteValueDictionary ObjectToDictionary(object value) | |
{ | |
var dictionary = new RouteValueDictionary(); | |
if (value != null) | |
{ | |
foreach (PropertyInfo property in value.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance) | |
.Where(prop => prop.GetIndexParameters().Length == 0 && | |
prop.GetMethod != null)) | |
{ | |
dictionary.Add(property.Name, property.GetValue(value)); | |
} | |
} | |
return dictionary; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment