Images as Action Links

An entry about asp.net mvc Publication date 8. August 2008 12:05

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")%>

Currently rated 3.7 by 7 people

  • Currently 3.714286/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Comments

Powered by BlogEngine.NET 1.4.5.0

Welcome!

My name is Fredrik Kalseth, and this is my blog - thanks for visiting! I am fortunate enough to work with what I love for a living, and this blog is essentially the biproduct of that.

I work as a senior consultant for Capgemini, and am also an active participant in the Norwegian .NET community, as an avid attendee but also as a speaker (most recently at NNUG and MSDN Live).

As a developer, I have a wide circle of interest. My primary passion is for agile, test-driven development, with focus on best practices and clean code. That said, I also love to work on the frontend, especially with web development.

On Twitter? My handle is fkalseth. On LinkedIn? I`m there too.


Disclaimer

This is a personal blog; any opinions expressed here are my own and do not necessarily reflect those of my employer. All content herein is my own original creation, and as such is protected by copyright law. Unless otherwise stated, all source code posted on this blog is freely usable under the Microsoft Permissive License.

What Readers Talk About

Comment RSS