February 16, 2012 at 2:58 AM
—
Website Sorcery
A lot of people override the Ajax helper to create an Ajax.ImageActionLink. This is fine but in some instances it's easier to use an Html.ImageActionLink.
For example, I had a requirement to return a file in a response stream - something that isn't possible with the Ajax method.
The code is fairly simple, and easy to customize to your requirements:
public static MvcHtmlString ImageActionLink(this HtmlHelper helper, string imagePath,
string actionName, string controllerName, object routeValues, object imageAttributes,
object linkAttributes)
{
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext,
helper.RouteCollection);
var aBuilder = new TagBuilder("a");
aBuilder.MergeAttributes(new RouteValueDictionary(linkAttributes));
aBuilder.MergeAttribute("href", urlHelper.Action(actionName, controllerName,
routeValues));
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttributes(new RouteValueDictionary(imageAttributes));
imgBuilder.MergeAttribute("src", imagePath);
aBuilder.InnerHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
return new MvcHtmlString(aBuilder.ToString(TagRenderMode.Normal));
}