Search code examples
sitecoresitecore7

Sitecore Building a single page from child node data


I have a Sitecore structure of items which comprises of

  • Range
    • Product 1
      • Product Name (text)
      • Product Image (image)
    • Product 2
      • Product Name (text)
      • Product Image (text)

I need to make a single page view that iterates through each of these nodes and collects and outputs the data for each - can anyone assist in the method I would best use to do this?

Sorry if this is a basic question but any example code would be appreciated.


Solution

  • You should really think about just using a single product template with a Product Name field and a Product Image field instead of having items with single fields under the product. But if this is your requirement, this is how you would do it.

    SubLayout (or layout if need be)

    <div>
        <sc:Text runat="server" id="txtProductName" Field="ProductName"/>
        <sc:Image runat="server" id="imgProductImage" Field="ProductImage"/>
    </div>
    

    Then in code behind you would take the current item (the product and find the child item that corresponds to what you are looking for and assign it as the field item.

        private void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindData();
            }
        }
    
        private void BindData()
        {
            txtProductName.Item = Sitecore.Context.Item.Children.FirstOrDefault(x => x.TemplateID == Constants.Templates.ProductName);
            imgProductImage.Item = Sitecore.Context.Item.Children.FirstOrDefault(x => x.TemplateID == Constants.Templates.ProductImage);
        }
    

    In my example I am resolving it looking for an item of template type X, but you could go by name or some other way of knowing.