开发者

Custom Helper using the model

开发者 https://www.devze.com 2023-01-14 04:50 出处:网络
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:

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.In开发者_开发技巧gredients %> </div>

Thank you!


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" />


  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>
0

精彩评论

暂无评论...
验证码 换一张
取 消