【发布时间】:2012-02-10 01:06:25
【问题描述】:
如何用razor helper方法做到这一点?
下面链接的问题的答案使用扩展方法。 Action Image MVC3 Razor
【问题讨论】:
-
我刚刚用谷歌搜索了它!我不知道从哪里开始。由于各种依赖关系,此解决方案不能仅在辅助方法中复制。
标签: asp.net-mvc-3 razor
如何用razor helper方法做到这一点?
下面链接的问题的答案使用扩展方法。 Action Image MVC3 Razor
【问题讨论】:
标签: asp.net-mvc-3 razor
我不太确定为什么扩展方法不合适,但这样的东西应该可以工作:
@helper ActionImage(string action, object routeValues, string imagePath, string alt) {
<a href="@Url.Action(action, routeValues)">
<img src="@Url.Content(imagePath)" alt="@alt">
</a>
}
这只是我的想法,所以你的里程可能会有所不同。您还应该能够将问题中提供的实现用作@functions { } 块而不是扩展方法。
【讨论】:
WebViewPage<T> 或 App_Code 的视图中?
这是我的图像 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());
}
希望对你有帮助
【讨论】: