How To: Create an ActionLink with a Twitter Bootstrap icon in MVC4
By rickvdbosch
- 2 minutes read - 230 wordsTwitter Bootstrap is a… “Sleek, intuitive, and powerful front-end framework for faster and easier web development.” One of the nice things in Bootstrap is you can use icons from Glyphicons. To use these, you can simply use this markup <i class="icon-fire"></i>
to get a nice fire icon.
Translating this into an ActionLink styled as a button in an MVC4 application would look something like the following:
@Html.ActionLink("<i class="icon-fire"></i> Invent fire", "fire", new { @class = "btn" })
Unfortunately, this renders as follows:
The reason this is not rendered correctly is because Html.ActionLink HtmlEncodes the text you pass in the actionLink parameter. You can check this by opening the System.Web.Mvc assembly in your disassembler of choice, and having a look at the GenerateLinkInternal method on the HtmlHelper class. It HtmlEncodes the linkText, and doesn’t have any option to have it not do that. To solve this, I wrote an extension method called NoEncodeActionLink, looking like this:
public static IHtmlString NoEncodeActionLink(this HtmlHelper htmlHelper, string linkText, string action, object htmlAttributes)
{
UrlHelper urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
TagBuilder builder = new TagBuilder("a");
builder.InnerHtml = linkText;
builder.Attributes["href"] = urlHelper.Action(action);
builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
return MvcHtmlString.Create(builder.ToString());
}
Calling the new overload (don’t forget to add a using statement to the namespace holding the extension method), the linkText parameter is not HtmlEncoded, which means the ActionLink now renders fine, including the icon (and the button style):
Hope this helps.