简体   繁体   中英

Always add only 1 item to the list C#

I want to add Object List to the Session.But in my code always create Fresh Object(always only 1 item in the list)

DTO

 public class CartTotal
{
    public decimal SubTotal { get; set; }
    public decimal DeliveryCharges { get; set; }
    public decimal GrandTotal { get; set; }
    public int CurrentItemCount { get; set; }

    public List<Items> items { get; set; }
}

Items

 public class Items
{
    public int ItemId { get; set; }
    public string ItemCode { get; set; }
    public string ItemName { get; set; }
    public string ImageUrl { get; set; }
    public int? ItemBadge { get; set; }
    public DateTime? AddedDate { get; set; }
    public int? AddedBy { get; set; }


}

Session

  public CartTotal ItemsHolder
    {
        get
        {
            object ItemsSession = Session["ItemSession"] as CartTotal;

            if (ItemsSession == null)
            {
                ItemsSession = new CartTotal();
                Session["ItemSession"] = ItemsSession;
            }

            return (CartTotal)ItemsSession;
        }
    }

I've tried to add items to the list like below.But always it add fresh item and(always only 1 item in the list.)

            ItemsHolder.items = new List<Items>(); // When i comment this line,below code not working.

            ItemsHolder.items.Add(new Items() {
                ItemId = items.ItemId,
                ItemName = items.ItemName,
                ItemPrice = items.ItemPrice,
                ImageUrl = items.ImageUrl,
                ItemCode = items.ItemCode
            });

In class CartTotal , write

public List<Items> items { get; } = new List<Items>();

This creates a new list once in each CartTotal object. In addition, the items property is read-only. Therefore, you cannot add it another list by inadvertence.

Delete the line

ItemsHolder.items = new List<Items>(); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM