2012-02-10 67 views

回答

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 { }块,而不是扩展方法。

+0

不能使用@ Url.Something,必须包含一些东西? – Ante 2012-02-10 12:55:12

+0

调用@ System.Web.Mvc.UrlHelper.Action不起作用 – Ante 2012-02-10 13:16:55

+0

@Ante你在哪里定义这个帮助器?在从“WebViewPage ”或“App_Code”继承的视图中? – 2012-02-10 13:43:01

0

这里是我的形象HTML辅助的简单例子

关于HTML辅助小文章,以及如何分类:G642.44它在HTML辅助的另一个

http://www.sexyselect.net/blog/post/2011/08/16/Writing-a-Razor-MVC3-HTML-Helpers

例如 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()); 
     } 

希望你找到它有用

+0

我试图找到帮助方法的解决方案..类似的方法描述在引用的链接,但我没有使用@帮助方法.. – Ante 2012-02-10 10:33:16