Patrick Desjardins Blog
Patrick Desjardins picture from a conference

Asp.Net MVC Html Helper to create link with an image

Posted on: 2013-04-18

You can use the default Html Helper to have a text url. This is most of the time sufficient but when came the scenario that you want an image to be a link, you are alone. You can create every time a link that will contain an image. But, with Asp.Net MVC, one nicest way to do it would be with an Html Extension. The main reason is that you won't have to repeat the code every time.

So, if we take the ActionLink html helper we would use it this way.

 @Html.ActionLink("Text to display", "ActionNameHere", "ControllerNameHere", new { id = 123 }, new{@class="myClass"}) 

As you can see, this overload take the text to display, the action name to redirect to and the controller which belong the action. Then, we have the route value which in this example send an id to the action and finally an html attribute which let you configure the link accordingly to some html attributes you desire.

What we want to do it almost the same but adding an image.

public MvcHtmlString ActionImage(this HtmlHelper htmlHelper, string controller, string action, object routeValues, string imagePath, string alternateText = "", object htmlAttributes = null) {
  var anchorBuilder = new TagBuilder("a"); 
  var url = new UrlHelper(HtmlHelper.ViewContext.RequestContext);

  anchorBuilder.MergeAttribute("href",url.Action(action,controller,routeValues)); 
  var imgBuilder = new TagBuilder("img"); 
  imgBuilder.MergeAttribute("src", url.Content(imagePath)); 
  imgBuilder.MergeAttribute("alt", alternateText);

  var attributes = (IDictionary<string, object>) HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); 
  imgBuilder.MergeAttributes(attributes); 
  string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);

  anchorBuilder.InnerHtml = imgHtml; 
  return MvcHtmlString.Create(anchorBuilder.ToString()); 
} 

The first parameter let you extend the HtmlHelper. This will let you use your new method with the @Html keyword. The 4 next parameters is the required parameters. THe first one is the controller, then the action, the route value and the image path. Finally, we can specify if desired an alternated text and additional html attributes.

The first part will create the link. It uses the RequestContext and the UrlHelperto create the link. In fact, it will build from the controller, the action and the route values an url well formed from the routing schema of your Asp.Net MVC website.

The last part build the image and add it into the link. Finally, we merge the attribute we passed to the image. We could also do the same to have html attribute for the link.

Here is how to html helper can be used.

 @Html.ActionImage("Workout", "Delete", new { id = @workout.Id }, "/images/bluetrash.png", "Delete", new { id="deletebutton"})