【发布时间】:2016-05-18 22:55:06
【问题描述】:
我将 Json 返回到 Ajax 以更改我页面上的一些 html。 c# 看起来像这样:
public JsonResult AddToCart(int id, int sizeid, int sizeVal, int catID)
{
Cake C = db.Cakes.Find(id);
List<Item> cart = new List<Item>();
if (Session["cart"] == null)
{
cart.Add(new Item(C, 1, sizeid, sizeVal));
Session["cart"] = cart;
}
else
{
cart = (List<Item>)Session["cart"];
int index = isExisting(id, sizeid);
if (index == -1)
cart.Add(new Item(C, 1, sizeid, sizeVal));
else
cart[index].Quantity++;
Session["cart"] = cart;
}
return Json(JsonConvert.SerializeObject(cart.Select(b => new { b.Cake.Image, b.Cake.Name, b.SizeVal, b.Quantity, b.Cake.CakeDetails.Where(c => c.SizeID == b.Size).FirstOrDefault().Price, b.Cake.CakeID, b.Size }),
Formatting.Indented,
new JsonSerializerSettings { }), JsonRequestBehavior.AllowGet);
}
我有两类蛋糕,即纸杯蛋糕和蛋糕。蛋糕有两种尺寸和两种价格,而纸杯蛋糕没有尺寸。
当我在蛋糕上运行这个方法时,它运行良好,但是当我在纸杯蛋糕上运行它时,它给了我这个错误:
System.NullReferenceException
这是因为纸杯蛋糕没有上面代码中所写的b.Size 或c.SizeID。
有没有办法在cart.Select(b => new { ... }) 方法中允许空值?
或者我可以在cart.Select(b => new { ... })中放一个if语句或其他东西
我想使用相同的 AddToCart 方法返回蛋糕和纸杯蛋糕。我该怎么做?
【问题讨论】:
标签: c# json ajax serialization parameters