How to do it with razor helper method?
The answer at question linked below uses extension method. Action Image MVC3 Razor
How to do it with razor helper method?
The answer at question linked below uses extension method. Action Image MVC3 Razor
I'm not really sure why an extension method isn't suitable, but something like this should work:
@helper ActionImage(string action, object routeValues, string imagePath, string alt) {
<a href="@Url.Action(action, routeValues)">
<img src="@Url.Content(imagePath)" alt="@alt">
</a>
}
That is just off the top of my head, so your milage may vary. You should also be able to use the implementation provided in the question as a @functions { }
block rather than an extension method as well.
Here is simple example of my image html helper
small article about Html helpers and how to intergrate it
http://www.sexyselect.net/blog/post/2011/08/16/Writing-a-Razor-MVC3-HTML-Helpers
example of another in html helpers http://www.aspnetwiki.com/page:creating-custom-html-helpers
Sample Code
/// <summary>
/// Insights the traffic light image.
/// </summary>
/// <param name="html">The HTML.</param>
/// <param name="trafficLight">The traffic light.</param>
/// <returns>Image for the current traffic light. If not recognised writes name ot he light.</returns>
public static MvcHtmlString InsightTrafficLightImage(this HtmlHelper html, TrafficLight trafficLight)
{
StringBuilder result = new StringBuilder();
string color = string.Empty;
string hoverText = string.Empty;
switch (trafficLight)
{
case TrafficLight.Amber:
{
color = "Yellow";
hoverText = "Work in progress";
break;
}
case TrafficLight.Green:
{
color = "green";
hoverText = "Complete";
break;
}
case TrafficLight.Red:
{
color = "red";
hoverText = "Not yet started";
break;
}
case TrafficLight.Black:
case TrafficLight.Unknown:
default:
{
break;
}
}
if (!string.IsNullOrEmpty(color))
{
TagBuilder img = new TagBuilder("img");
img.MergeAttribute("src", string.Format("/Content/images/traffic_light_{0}.gif", color));
img.MergeAttribute("alt", hoverText);
img.MergeAttribute("title", hoverText);
result.Append(img.ToString());
}
else
{
result.Append(Enum.GetName(typeof(TrafficLight), trafficLight));
}
return MvcHtmlString.Create(result.ToString());
}
Hope you find it helpfull