When creating a link to a controller action in ASP.NET MVC, using the generic ActionLink method is preferable, because it allows for strongly typed links that are refactoring friendly:
<%= Html.ActionLink<PageController>(p => p.Edit(ViewData.Model.PageId), "edit") %>
However, what if we want to have an image that links to an action? You might think that you could combine the ActionLink and Image helpers like this:
<%= Html.ActionLink<PageController>(p => p.Edit(ViewData.Model.PageId),
Html.Image("~/Content/Icons/pencil.png", "edit")) %>
That won’t work though, because the ActionLink method html encodes the text you pass it. I’ve created a quick and dirty extension method that works around this:
public static string ActionLinkImage<T>(this HtmlHelper helper,
Expression<Action<T>> action,
string imageRelativeUrl,
string alt)
where T : Controller
{
string html = String.Format(helper.ActionLink(action, "{0}"),
helper.Image(imageRelativeUrl, alt));
return html;
}
This now lets me write:
<%= Html.ActionLinkImage<PageController>(p => p.Edit(ViewData.Model.PageId),
"~/Content/Icons/pencil.png", "edit")%>