I'm trying to return a ContentPart from the HTTP session in a Driver. Here is the code for my Driver and ContentPart:
public class UnpersistedPartDriver : ContentPartDriver<UnpersistedPart>
{
public Localizer T { get; set; }
private readonly IHttpContextAccessor _httpContextAccessor;
public UnpersistedPartDriver(IHttpContextAccessor httpContextAccessor) {
T = NullLocalizer.Instance;
_httpContextAccessor = httpContextAccessor;
}
/// <summary>
/// This method is responsible for displaying your part in the frontend.
/// </summary>
/// <param name="part">Your part.</param>
/// <param name="displayType"></param>
/// <param name="shapeHelper"></param>
/// <returns></returns>
protected override DriverResult Display(UnpersistedPart part, string displayType, dynamic shapeHelper)
{
var session = _httpContextAccessor.Current().Session;
var cart = session["Cart"] as UnpersistedPart;
if (cart == null) {
cart = new UnpersistedPart();
session["Cart"] = cart;
}
return ContentShape("Parts_Jumpstart_Unpersisted",
() => shapeHelper.Parts_Jumpstart_Unpersisted(ContentPart: part));
}
// There is nothing to edit and update, so we don't need Editor methods.
}
public class UnpersistedPart : ContentPart
{
public UnpersistedPart()
{
this.Items = new List<Item>();
this.Items.Add(new Item { Id = 1, Title = "Book 1", Price = "130.00", Quantity = "1" });
this.Items.Add(new Item { Id = 2, Title = "Book 2", Price = "145.00", Quantity = "2" });
this.Items.Add(new Item { Id = 3, Title = "Book 3", Price = "150.00", Quantity = "3" });
}
public IList<Item> Items;
public string Total
{
get
{
return Items.Sum(i => i.Total).ToString();
}
}
public string SessionId;
}
[Serializable]
public class Item
{
public int Id;
public string Title;
public string Price;
public string Quantity;
public decimal Total { get { return decimal.Parse(Price) * int.Parse(Quantity); } }
}
When I change part to cart:
return ContentShape("Parts_Jumpstart_Unpersisted",
() => shapeHelper.Parts_Jumpstart_Unpersisted(ContentPart: part));
to:
return ContentShape("Parts_Jumpstart_Unpersisted",
() => shapeHelper.Parts_Jumpstart_Unpersisted(ContentPart: cart));
it doesn't display anything. I get an empty article tag:
<article class="content-item book" shape-id="0"></article>