views:

18

answers:

2

Hi,

I'm pretty new to MVC and just read an article about helpers. Now I have this code on the 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>

How do I go on and create a Helper that would replace that code with something simpler like:

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

Thank you!

+1  A: 

you'll need to make an HtmlHelper Extension Method

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;
        }
    }
}

Then you can call <%=Html.Ingredients(Model.Products_Ingredients) %>

make sure you add this assembly reference to the page

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

or to your Web.Config so all pages have access

<pages>
    <namespaces>
        <add namespace="User.Extensions" />
hunter
Exactly the same...beat me to it. Only thing I did not use an extension method i just used a helper class and included.
Nix
Thanks for the quick response. I've tried that and now I've got 2 different errors.When I add the loop: "foreach (var e in productIngredients)" I get this error: "foreach statement cannot operate on variables of type 'Products_Ingredients' because 'Products_Ingredients' does not contain a public definition for 'GetEnumerator'"
user
Also, in the View I get this error: "The best overloaded method match for 'HtmlHelperExtensions.Ingredients(Products_Ingredients)' has some invalid arguments"
user
can you update your question with the Product_Ingredients class or your model?
hunter
ok I found the problem. I had to declare the method as:public static string Ingredients(IEnumerable<Products_Ingredients> productIngredients).Thank you
user
glad to hear it, mark mine as the answer?
hunter
A: 
  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;
    }
  }

In your page add

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

  <div class="display-label">Ingredients: <%: MyHelpers.Ingredients(Model.Products_Ingredients) %> </div>
Nix
same errors as above
user
See above. Its an IEnumerable.
Nix