如何使用razor helper方法?
以下链接的答案使用扩展方法。 Action Image MVC3 Razor
答案 0 :(得分:2)
我不确定为什么扩展方法不合适,但这样的事情应该有效:
@helper ActionImage(string action, object routeValues, string imagePath, string alt) {
<a href="@Url.Action(action, routeValues)">
<img src="@Url.Content(imagePath)" alt="@alt">
</a>
}
这只是我的头顶,所以你的milage可能会有所不同。您还应该能够将问题中提供的实现用作@functions { }
块而不是扩展方法。
答案 1 :(得分:0)
以下是我的图片html帮助
的简单示例关于Html助手以及如何整合它的小文章
http://www.sexyselect.net/blog/post/2011/08/16/Writing-a-Razor-MVC3-HTML-Helpers
html助手中的另一个例子 http://www.aspnetwiki.com/page:creating-custom-html-helpers
示例代码
/// <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());
}
希望你发现它有用