h3mm3's blog

Stories from behind the keyboard

  • RSS
  • Twitter

If you want to use HtmlHelper.ActionLink(..) extension method to produce something like a clickable image, you could get into trouble. In effect, the “linkText” string passed to HtmlHelper.ActionLink is automatically HTML-encoded by the helper method before producing the desired anchor element. So it seems somewhat impossible to make this sort of invocation work:

<%= Html.ActionLink(
"<img src='myImage.png'/>",
'TheAction', ...) %>
My solution to this problem was to write an extension method like this one:
public static string ActionLinkEx(
  this HtmlHelper h, string htmlLinkText,
  string actionName, string controllerName,
  object routeValues, object htmlAttributes)
  var builtCode = h.ActionLink(
    "*",actionName, controllerName,
    routeValues, htmlAttributes);
  return builtCode.Replace("*",htmlLinkText);
The method just wraps the standard HtmlHelper.ActionLink(..). This one prepares an HTML text made by a clickable asterisk (*) linking to the desired action method. Then my helper method replaces the text of the link (the asterisk) with the desired HTML code (passed using the htmlLinkText input parameter).

No comments: