Created
February 6, 2012 19:28
-
-
Save dgomesbr/1754249 to your computer and use it in GitHub Desktop.
ASP.NET MVC 2 Html.ImageActionLink Helper using Microsoft.Web.Mvc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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