Hey,
I'm an intern and new with dynamic web.
I am struggling to transform the product data to a csv.
The code I currently have is displaying the id and name, but not the variantId, or Numbe, these show as empty:
@using Dynamicweb.Rendering;
@using Dynamicweb.Ecommerce.ProductCatalog;
@using System.Collections.Generic;
@using System.Text;
@inherits ViewModelTemplate<ProductListViewModel>
@functions
{
public enum FieldType
{
System,
Standard
};
public class Field
{
public string ID { get; set; }
public FieldType FieldType { get; set; }
public string Label { get; set; }
public Field(string id, string label, FieldType type)
{
ID = id;
Label = label;
FieldType = type;
}
}
public List<Field> GetFields(ProductViewModel productViewModel)
{
var fields = new List<Field>();
if (productViewModel == null)
{
return fields;
}
fields.Add(new Field("Id", "Product Id", FieldType.System));
fields.Add(new Field("VariantId", "Variant id", FieldType.System));
fields.Add(new Field("Number", "Number", FieldType.Standard));
fields.Add(new Field("Name", "Name", FieldType.Standard));
return fields;
}
public string GenerateCsv()
{
var fields = GetFields(Model.Products.FirstOrDefault());
var allHeaders = fields.Select(x => new KeyValuePair<string, string>(x.ID, x.Label)).ToList();
var headerSystemNames = allHeaders.Select(x => x.Key).ToList();
StringBuilder contentBuilder = new System.Text.StringBuilder();
contentBuilder.Append(Encoding.UTF8.GetString(Encoding.UTF8.GetPreamble()));
var headerLine = string.Join(";", allHeaders.Select(x => String.Format("\"{0}\"", x.Value))).ToString();
contentBuilder.AppendLine(headerLine);
var productsOuput = new StringBuilder();
foreach (var product in Model.Products)
{
var values = new string[headerSystemNames.Count];
values[headerSystemNames.IndexOf("Id")] = product.Id;
values[headerSystemNames.IndexOf("VariantId")] = product.VariantId;
values[headerSystemNames.IndexOf("DefaultVariantId")] = product.DefaultVariantId;
values[headerSystemNames.IndexOf("Number")] = product.Number;
values[headerSystemNames.IndexOf("Name")] = product.Name;
productsOuput.AppendLine(string.Join(";", values.Select(x => String.Format("\"{0}\"", (x == null ? "" : x.Replace("\"", "'"))))));
}
contentBuilder.Append(productsOuput.ToString());
return contentBuilder.ToString();
}
}
@GenerateCsv()
This is the result:
The variant Id and number are empty. I dont need the defaultVariantId that was just for testing.
Thanks in advance!