Hello Everyone I am trying to add items to cart using Session But I am facing That issue System.NullReferenceException: Object reference not set to an instance of an object. Check This Image
Here is my View Where I want to show Cart items
@foreach (var item in (List<Product>)Session["MyCart"])
{
<li>
<a href="#" ><img src="@Url.Content(item.Product_Picture)" alt="" /></a>
<h6><a href="#">@item.Product_Name </a></h6>
<p>1x -Rs <span >@item.Product_SalePrice</span></p>
</li>
}
</ul>
Now This is my Action Controller
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");
}
CodePudding user response:
You can check if your Session
is not null on your View
before you try to cast it and access its properties:
@if(Session["MyCart"] != null)
{
foreach (var item in (List<Product>)Session["MyCart"])
{
<li>
<a href="#" ><img src="@Url.Content(item.Product_Picture)" alt="" /></a>
<h6><a href="#">@item.Product_Name </a></h6>
<p>1x -Rs <span >@item.Product_SalePrice</span></p>
</li>
}
</ul>
}
else
{
<h2>Cart is empty</h2>
}
You should create a partial view for your carts and then refer it where it is required. There are many tutorial for partial views creation and usage You can refer to this tutorial