Today I ran into a need where I wanted to create the html needed to render an image as a link and I wanted that clicking of that image to route to a controller action. The off the shelf Html helper that comes with the MVC frame does not support this by default (there is a work around) so I decided to create my own.
Here is the desired HTML output I am looking for:
<a href="[RouteHere]" target="_blank"><img src="[ImagePath]" alt="[AltText]" style="border-style: none"/></a>
Here is the work around:
<a href="<%=Html.BuildUrlFromExpression<MyController>( x => x.MyRoute() ) %>" target="_blank"><img src="[ImagePath]" alt="[AltText]" style="border-style: none"/></a>
The workaround above simply uses the html helper for building url's from an expression and pops that into the HTML. This is a workable solution, but I would rather have the Html helper generate the Html needed.
Here is the code with the Html Helper:
<%= Html.ImageLink<MyController>( x => x.MyRoute(), "[ImagePath]", "[Target]", "[AltText]" )%>
I like the above a little better as it does not mix html code with a call to the html helper. I feel this syntax is a little cleaner.
Here is the Html Helper code:
public static string ImageLink<T>( this HtmlHelper helper, Expression<Action<T>> linkUrlAction,
string imageUrlPath, string linkTarget, string altText ) where T : Controller
{
string linkUrl = helper.BuildUrlFromExpression( linkUrlAction );
string outputUrl = string.Format( @"<a href='{0}' target='{1}'><img src='{2}' alt='{3}' style='border-style: none' /></a>", linkUrl, linkTarget, imageUrlPath, altText );
return outputUrl;
}
Please note that this helper method is built for my needs, if you need/want to have the html rendered a little differently then you will have to make the necessary modifications.
Hope this helps.
Till next time,
[----- Remember to check out DimeCasts.Net -----]
Posted
07-09-2008 9:10 AM
by
Derik Whittaker