Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ASP.NET MVC 2 Html.ImageActionLink Helper using Microsoft.Web.Mvc
// After using the Microsoft.Web.Mvc Html.ActionLink<TController>(... Expression<Action<TController>> action ...);
// I was unable to use that for a Image, so here's the code for it:
// **** :) no more magic strings for image linking to actions.
// usage:
// <%= Html.ImageActionLink<HomeController>(
// x => x.ChangeCulture(Culture.pt, this.Request.RawUrl),
// Culture.pt.ToString() + ".png")
// %>
public static class ContentHelper
{
public static readonly string CssPath = "~/Content/css/";
public static readonly string JsPath = "~/Content/javascript/";
public static readonly string ImgPath = "~/Content/images/";
public static string Css(this UrlHelper helper, string file)
{
return helper.Content(String.Format(CssPath + "{0}", file));
}
public static string Js(this UrlHelper helper, string file)
{
return helper.Content(String.Format(JsPath + "{0}", file));
}
public static string Img(this UrlHelper helper, string file)
{
return helper.Content(String.Format(ImgPath + "{0}", file));
}
public static MvcHtmlString ImageActionLink<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string imageSource) where TController : Controller
{
return ImageActionLink<TController>(helper, action, imageSource, (object) null);
}
public static MvcHtmlString ImageActionLink<TController>(this HtmlHelper helper, Expression<Action<TController>> action, string imageSource, object htmlAttributes ) where TController : Controller
{
var valuesFromExpression = Microsoft.Web.Mvc.Internal.ExpressionHelper.GetRouteValuesFromExpression<TController>(action);
var urlHelper = new UrlHelper(helper.ViewContext.RequestContext, helper.RouteCollection);
var aBuilder = new TagBuilder("a");
aBuilder.MergeAttribute("href", urlHelper.Action((string)valuesFromExpression["Action"], (string)valuesFromExpression["Controller"], valuesFromExpression));
var imgBuilder = new TagBuilder("img");
imgBuilder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
imgBuilder.MergeAttribute("src", Img(urlHelper, imageSource));
aBuilder.InnerHtml = imgBuilder.ToString(TagRenderMode.SelfClosing);
return MvcHtmlString.Create(aBuilder.ToString(TagRenderMode.Normal));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.