使用模型的自定义帮助

问题描述:

我对MVC很陌生,只是阅读了关于帮助者的文章。现在,我对这篇代码:使用模型的自定义帮助

<div class="display-label">Ingredients: 
     <% foreach (var e in Model.Products_Ingredients) 
     {%> 
      <%: e.Ingredient.Name%><br /> 
      <%: e.Percentage%> 
       <%if (e.Percentage != null) 
       {%> 
        % 
       <%}%> 
       <br /> 
     <%}%> 
    </div> 

我怎么去上,并创建一个助手将取代该代码与像更简单的东西:

<div class="display-label">Ingredients: <%: MyHelpers.Ingredients %> </div> 

谢谢!

你需要做的的HtmlHelper扩展方法

public namespace User.Extensions 

    public static HtmlHelperExtensions 
    { 
     public static string Ingredients(this HtmlHelper, Product_Ingredients productIngredients) 
     { 
      string result = string.Empty; 
      // loop through your ingredients and build your result, could use TagBuilder, too 
      return result; 
     } 
    } 
} 

然后就可以调用<%=Html.Ingredients(Model.Products_Ingredients) %>

确保你这个集引用添加到网页

<%@ Import Namespace=User.Extensions" %> 

,或者你Web.Config使所有页面都可以访问

<pages> 
    <namespaces> 
     <add namespace="User.Extensions" /> 
+0

一模一样的......打我给它。只有我没有使用扩展方法,我只是使用了一个辅助类并包含在内。 – Nix 2010-09-01 13:30:01

+0

感谢您的快速响应。我试过了,现在我有两个不同的错误。我得到这个错误:“foreach语句不能对'Products_Ingredients'类型的变量进行操作,因为'Products_Ingredients'不包含'GetEnumerator'的公共定义” – user 2010-09-01 13:46:46

+0

此外,在视图中我得到这个错误:“最好的重载方法匹配'HtmlHelperExtensions .Ingredients(Products_Ingredients)'有一些无效参数” – user 2010-09-01 13:47:53

public class MyHelpers 
    { 
    public static string Ingredients(IEnumerable<Products_Ingredients> pi) 
    { 
     //html code as string 
     // <%: pi.Ingredient.Name%><br /> 
     // <%: pi.Percentage%> 
     //  <%if (pi.Percentage != null) 
     //  {%> 
     //   % 
     //  <%}%> 
     //  <br /> 
     return htmlCode; 
    } 
    } 

在你的页面中添加

<%@ Import Namespace=namespace.MyHelpers" %> 

<div class="display-label">Ingredients: <%: MyHelpers.Ingredients(Model.Products_Ingredients) %> </div> 
+0

与上面相同的错误 – user 2010-09-01 14:02:37

+0

请参阅上文。它是一个IEnumerable。 – Nix 2010-09-01 14:51:47