Create a Product Page

Products are content items within Sitecore. Use MVC to display product details.

Complete the following prerequisites:

At the Content Editor

  1. Create a view for your products called _Products.cshtml and use it in the layout controls in Sitecore. You need a view for relationships displayed on the product page called _ProductSummary.cshtml.

    _Products.cshtml

    @model ProductViewModel
    @{
        var mod = (ProductViewModel)Model;
    }
     
    <div class="row">
        <div class="span5" id="productImages">
            <img src="@mod.FirstImagePath(ImageSize.Large)" alt="">
        </div>
        <div class="span4">
            <h3>@Model.DisplayNameRender</h3>
            <p>
                @Model.DescriptionRender
            </p>
        </div>
        <div class="span3">
            <h3>Price</h3>
            <span id="price">@Model.ListPriceRender</span>
        </div>
    </div>
    <div class="row">
        <div class="span12">
            @if (Model.Upsells != null && Model.Upsells.Any())
            {
                <h3>Upsells</h3>    
                <ul class="thumbnails" id="productUpsells">
                    @foreach (var product in Model.Upsells)
                    {   
                        <li class="span3">
                            @Html.Partial("~/Views/Catalog/_ProductSummary.cshtml", new ProductViewModel(product))
                        </li>  
                    }
                </ul>
            }
        </div>
    </div>

    _ProductSummary.cshtml

    @model ProductViewModel
    @{
        var mod = (ProductViewModel)Model;
    }
     
    <a href="@Sitecore.Links.LinkManager.GetDynamicUrl(mod.Item)">
        <div class="thumbnail">
            <img src="@mod.FirstImagePath(ImageSize.Detail)" alt="">
            <div class="productLabel">
                <span class="label label-success">@mod.ListPriceRender</span><span class="label label-productName">@mod.DisplayNameRender</span>
            </div>
            <div class="detailsFloatOver">
                    <h4>@mod.DisplayNameRender </h4>
                    <p>@mod.ListPriceRender</p>
            </div>
        </div>
    </a>
    
  2. Create your basic view model for products.
        public class ProductViewModel : Sitecore.Mvc.Presentation.RenderingModel, IImageEntity
        {
            private Item _item;
     
            public ProductViewModel() {}
            public ProductViewModel(Item item)
            {
                this._item = item;
                Upsells = new List<Item>();
            }
     
            public override Item Item
            {
                get
                {
                    if (this._item == null)
                        return base.Item;
     
                    return this._item;
                }
            }
     
            public string ProductId 
            { 
                get { return this.Item.Name; }
                set { this.Item.Name = value; }
            }
     
            public string Description { get; set; }
            public HtmlString DescriptionRender
            {
                get { return PageContext.Current.HtmlHelper.Sitecore().Field("Description", this.Item); }
            }
     
            public string DisplayName { get; set; }
            public HtmlString DisplayNameRender
            {
                get { return PageContext.Current.HtmlHelper.Sitecore().Field(Sitecore.FieldIDs.DisplayName.ToString(), this.Item); }
            }
     
            public decimal? ListPrice
            {
                get
                {
                    var selectedCurrency = HttpContext.Current.Request.Cookies["currency"];
                    if (selectedCurrency != null)
                    {
                        if (this.Item["Price_" + selectedCurrency.Value] != null)
                        {
                            return decimal.Parse(this.Item["Price_" + selectedCurrency.Value].Replace("$", string.Empty), CultureInfo.InvariantCulture);
                        }
                    }
     
                    return decimal.Parse(this.Item["ListPrice"].Replace("$", string.Empty), CultureInfo.InvariantCulture);
                }
     
                set
                {
                    this.Item["ListPrice"] = value.ToString();
                }
            }
     
            public HtmlString ListPriceRender
            {
                get
                {
                    var selectedCurrency = HttpContext.Current.Request.Cookies["currency"];
                    if (selectedCurrency != null)
                    {
                        if (!string.IsNullOrEmpty(this.Item["Product_Price_" + selectedCurrency.Value]))
                        {
                            return PageContext.Current.HtmlHelper.Sitecore().Field("Product_Price_" + selectedCurrency.Value, this.Item);
                        }
                    }
     
                    return PageContext.Current.HtmlHelper.Sitecore().Field("ListPrice", this.Item);
                }
            }
     
            public string ImageFilename
            {
                get { return this.Item["Image_filename"]; }
                set { this.Item["Image_filename"] = value; }
            }
     
            public List<Item> Upsells { get; set; }
     
            public void Initialize(Rendering rendering)
            {
                base.Initialize(rendering);
            }
        }
    
  3. The MVC action controller can use the following sections of code to retrieve info about the product.

    The example shown below displays product image, name, description, price and relationships. Relationships are a field on the item, where variants would be children of the item.

            public ActionResult Product()
            {
                var productViewModel = GetProductViewModel(this.Item, this.CurrentRendering);
                return View(this.CurrentRenderingView, productViewModel);
            }
    
            protected ProductViewModel GetProductViewModel(Item productItem, Rendering rendering)
            {
                if (HttpContext.Items[_CurentProductViewModelKeyName] == null)
                {
                    var productViewModel = new ProductViewModel();
                    productViewModel.Initialize(rendering);
                    
                    // get upsells
                    if (productItem != null && productItem.Fields.Contains(CommerceConstants.KnownFieldIds.RelationshipList) && !string.IsNullOrEmpty(productItem[CommerceConstants.KnownFieldIds.RelationshipList]))
                    {
                        var upsells = new List<Item>();
                        RelationshipField field = new RelationshipField(productItem.Fields[CommerceConstants.KnownFieldIds.RelationshipList]);
     
                        if (field != null)
                        {
                            // display the upsells for this productItem
                            var relationships = GetRelationshipsFromField(field, "upsell");
                            if (relationships != null)
                            {
                                upsells = relationships;
                            }
                        }
     
                        productViewModel.Upsells = upsells;
                    }
     
                    HttpContext.Items[_CurentProductViewModelKeyName] = productViewModel;
                }
     
                return (ProductViewModel)HttpContext.Items[_CurentProductViewModelKeyName];
            }
     
            /// <summary>
            /// Gets a lists of target items from a relationship field
            /// </summary>
            /// <param name="field">the relationship field</param>
            /// <param name="relationshipName">the relationship name, for example upsell</param>
            /// <returns>a list of relationship targets or null if no items found</returns>
            protected List<Item> GetRelationshipsFromField(RelationshipField field, string relationshipName)
            {
                IEnumerable<Item> relationships = field.GetRelationshipsTargets(relationshipName);
                return relationships != null ? new List<Item>(relationships) : null;
            }
    
Previewing a product from within the Sitecore content editor displays a page with details about that product