大家好我正在嘗試使用 Session 將專案添加到購物車但我面臨這個問題 System.NullReferenceException: Object reference not set to an object of an instance。 檢查此影像
這是我想在哪里顯示購物車物品的視圖
@foreach (var item in (List<Product>)Session["MyCart"])
{
<li>
<a href="#" class="photo"><img src="@Url.Content(item.Product_Picture)" class="cart-thumb" alt="" /></a>
<h6><a href="#">@item.Product_Name </a></h6>
<p>1x -Rs <span class="price">@item.Product_SalePrice</span></p>
</li>
}
</ul>
現在這是我的動作控制器
public ActionResult AddtoCart(int id)
{
List<Product> list;
if (Session["MyCart"] == null)
{ list = new List<Product>(); }
else
{ list = (List<Product>)Session["MyCart"]; }
list.Add(db.Products.Where(p => p.Product_ID == id).FirstOrDefault());
Session["MyCart"] = list;
return RedirectToAction("Shop");
}
uj5u.com熱心網友回復:
在嘗試強制轉換并訪問其屬性之前,您可以檢查您的Session是否為空:View
@if(Session["MyCart"] != null)
{
foreach (var item in (List<Product>)Session["MyCart"])
{
<li>
<a href="#" class="photo"><img src="@Url.Content(item.Product_Picture)" class="cart-thumb" alt="" /></a>
<h6><a href="#">@item.Product_Name </a></h6>
<p>1x -Rs <span class="price">@item.Product_SalePrice</span></p>
</li>
}
</ul>
}
else
{
<h2>Cart is empty</h2>
}
您應該為您的購物車創建一個區域視圖,然后在需要的地方參考它。部分視圖的創建和使用有很多教程你可以參考這個教程
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/429169.html
上一篇:等待和手動任務處理的區別
