tags:

views:

2445

answers:

4

How can I do something similar to Html.ActionLink() except place the generated link around an Image instead of just spitting out the link?

+13  A: 
<a href="<%= Url.Action("ActionName", "ControllerName") %>">
    <img src="<%= Url.Content("~/Content/img/imgname.jpg") %>" /></a>

Obviously, if you do this more than once, write a helper for it. And fill in the other attributes of img/a. But this should give you the general idea.

Craig Stuntz
+6  A: 

Try something like this:

public static string ActionLinkWithImage(this HtmlHelper html, string imgSrc, string actionName)
{
    var urlHelper = new UrlHelper(html.ViewContext.RequestContext);

    string imgUrl = urlHelper.Content(imgSrc);
    TagBuilder imgTagBuilder = new TagBuilder("img");
    imgTagBuilder.MergeAttribute("src", imgUrl);
    string img = imgTagBuilder.ToString(TagRenderMode.SelfClosing);

    string url = UrlHelper.Action(actionName);

    TagBuilder tagBuilder = new TagBuilder("a") {
        InnerHtml = img
    };
    tagBuilder.MergeAttribute("href", url);

    return tagBuilder.ToString(TagRenderMode.Normal);
}

Hope this helps

eu-ge-ne
I suggest changing `TagRenderMode.Normal` to `TagRenderMode.SelfClosing` for the img; otherwise it renders as `<img...></img>` instead of `<img.../>`
Michael Haren
Good suggestion, thanks Michael
eu-ge-ne
A: 

You can create htmlhelper which can return image with link... As parameters you will pass to htmlhelper values like image path and link and in htmlhelper you will use StringBuilder to format html of that linked image properly...

cheers

Marko
+1  A: 

I liked eu-ge-ne's approach, but wanted a strongly typed version. After some digging I stole his and made it into a strongly-typed HtmlHelper extension.

You can find my version on my blog at the link above. Afterwards (always the case) I found another implementation here that also looks really good (although I haven't tried it). It definately looks more complete in implementation than mine.

Mirko