This is a follow up on my previous question: How do you map areas on icon set to buttons?
I decided to make my own HtmlHelper extension in order to create an ActionImage link, so I cannibalized some of the popular extensions posted on SO and got this:
// Controller/Action Image Link
public static MvcHtmlString ActionImage(this HtmlHelper html,
string controller, string action, object routeValues,
string imageSrc, string alternateText, object imageAttributes)
{
UrlHelper url = new UrlHelper(html.ViewContext.RequestContext);
// build the <img> tag
TagBuilder imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttribute("src", url.Content(imageSrc));
imgBuilder.MergeAttribute("alternateText", alternateText);
string imgHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
// build the <a> tag
TagBuilder anchorBuilder = new TagBuilder("a");
anchorBuilder.MergeAttribute("href", url.Action(action, controller, routeValues));
anchorBuilder.InnerHtml = imgHtml; // include the <img> tag inside
string anchorHtml = anchorBuilder.ToString(TagRenderMode.Normal);
return MvcHtmlString.Create(anchorHtml);
}
Now, the problem is that I have a CSS Sprite with and I don’t know how to make it work with the ActionImage extension method:
@Html.ActionImage("Account", "LogOn", null, Sprite.Image("~/App_Sprites/twitterlogin.png"), "", null)
I tried calling the ToString() method of the sprite, but it doesn’t return the URL. Is there another way to make this happen?
You could pass just the path to the sprite:
and then have the helper take care of generating the image using the
Sprite.Imagehelper: