Custom Helper с использованием модели - PullRequest
0 голосов
/ 01 сентября 2010

Я довольно новичок в 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>

Спасибо!

Ответы [ 2 ]

1 голос
/ 01 сентября 2010

вам нужно будет создать метод расширения 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 голосов
/ 01 сентября 2010
  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>
...