5

I try to add a new "Order" to my Session. I begin create a session in my Global.aspx file under Session_Start:

Session.Add("Cart", new WebShopData.Order());

At my login page i make a new Session:

 Session["userID"] = "User";
        ((Order)Session["Cart"]).UserID = userID;

Then at my shop page i want to add stuff to the session:

 if ((Order)Session["Cart"] != null)
((Order)Session["Cart"]).OrderRow.Add(new OrderRows({ArticleID = 2, Quantity = 1) });

At this last line i get att nullreference exception. Why could that be?


Here are my two classes:

   public class Order
   {
    public List<OrderRows> OrderRow { get; set; }
    public string Address { get; set; }
    public string City { get; set; }
    public string Zip { get; set; }
    public int UserID { get; set; }
   }

  public class OrderRows
  {
    public int ArticleID { get; set; }
    public int Quantity { get; set; }

    public override string ToString()
    {
            return string.Format("Artikel: {0}, Antal: {1}.\n", ArticleID, Quantity);
    }
  }
4

2 回答 2

4

您需要在使用 OrderRow 之前创建一个实例。我建议在构造函数中这样做......

将此添加到您的订单类

public class Order {
     ....other stuff...

    public Order() {
      OrderRow = new List<OrderRows>();
    }
}
于 2012-04-23T18:23:13.790 回答
2

当您创建新订单时,提交的 OrderRow 为空。您必须在 Order 构造函数上初始化 Order 行。

于 2012-04-23T18:21:42.033 回答