我对MVC很新,只读了一篇关于助手的文章。现在我在View上有这个代码:
<div class="display-label">Ingredients:
<% foreach (var e in Model.Products_Ingredients)
{%>
<%: e.Ingredient.Name%><br />
<%: e.Percentage%>
<%if (e.Percentage != null)
{%>
%
<%}%>
<br />
<%}%>
</div>
我如何继续创建一个Helper来代替那些更简单的代码:
<div class="display-label">Ingredients: <%: MyHelpers.Ingredients %> </div>
谢谢!
答案 0 :(得分:1)
你需要制作一个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" />
答案 1 :(得分:0)
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>