MVC ActionLink with Image the easy way

While reviewing some ASP.NET MVC code, I noticed a call to custom helper method with the sole purpose of creating an ActionLink with an image as the background.

My initial thought was "Let's do a search a find out how many calls we have to this extension method". The result was 22 times. When I asked the developer why create a helper method for something simple as this? I got the following response

  1. Extension methods are cool
  2. Cannot think of another way to achieve the same results other than writing the href tag and embedding an img tag within the href tag
  3. If I were to choose the above (bullet 2), refactoring will be painful
.imageAction
{
display: block;
background: url(../content/Images/buy_32.png) no-repeat;
}

The MVC call using the razor engine

@Html.ActionLink("Buy", "Buy", null, new { title = "Buy", @class = "imageAction" })

If this image needs to be changed in the future, we can do that by only changing the CSS class.

Why over complicate things?

Comments (3) -

great tip
thanks
Sue

Thanks, Saved lot of my time.

This did seem to be the simplest solution, but when I maximize the browser window, the image and link disappear. Here is the class I used and the HTML.LinkAction:

a.site-logo  {    
background: url(/Images/Sedgwickllp_Logo_Small.png) no-repeat top left;
display: block;
width: 125px;      
height: 38px;      
text-indent: -9999px;  /*hides the link text*/
  }

.site-title {
    color: #c8c8c8;
    display:block;
    font-family: Rockwell, Consolas, "Courier New", Courier, monospace;
    font-size: 2.3em;
    margin: -9999px;
}

.site-title a, .site-title a:hover, .site-title a:active {
    /*background: none;*/
    color: #c8c8c8;
    outline: none;
    text-decoration: none;
}
<div class="float-left">
                    <p class="site-title">@Html.ActionLink("siteHeader", "Index", "Home", null, new  { @class = "site-logo" })</p>
                </div>

Any idea why that would make the image disappear after the window is enlarged past a certain point?

Thanks!

Add comment