Когда я отлаживаю свой проект и добавляю элемент в корзину, я выдаю эту ошибку, не знаете, что делать?
System.InvalidCastException: 'Невозможно привести объект типа' System.Collections.Generic.List 1[ShoppingCartApp.Classes.CartItem]'
to type
'System.Collections.Generic.List
1 [ShoppingCartApp.Controllers.CartItem] '.'
В этой строке выдается ошибка @foreach (CartItem cartItem in (List<CartItem>)Session["shoppingCart"])
, на мой взгляд
Вот мой контролер
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ShoppingCartApp.ServiceReference1;
using ShoppingCartApp.Classes;
public class ShoppingCartController : Controller
{
Service1Client wcf = new Service1Client(); // Connection to WCF
// GET: ShoppingCart
public ActionResult ShoppingCart()
{
return View("ShoppingCart");
}
private int checkIfExisting(int id) // Checks session for existing products, increases quantity if product exists
{
List<CartItem> shoppingCart = (List<CartItem>)Session["shoppingCart"];
for (int x = 0; x < shoppingCart.Count; x++)
if (shoppingCart[x].Product.ProductID == id)
return x;
return -1;
}
public ActionResult RemoveFromCart(int id)
{
List<CartItem> shoppingCart = new List<CartItem>();
shoppingCart.Remove(new CartItem(wcf.GetProduct(id), 1));
Session["shoppingCart"] = shoppingCart;
return View("ShoppingCart");
}
public ActionResult AddToCart(int id) // Creates new session if one is not existing, adds item to cart, uses checkifexisting method to increase quantity
{
if(Session["shoppingCart"] == null)
{
List<CartItem> shoppingCart = new List<CartItem>();
shoppingCart.Add(new CartItem(wcf.GetProduct(id), 1));
Session["shoppingCart"] = shoppingCart;
} else
{
List<CartItem> shoppingCart = (List <CartItem>)Session["shoppingCart"];
int index = checkIfExisting(id);
if (index == -1)
shoppingCart.Add(new CartItem(wcf.GetProduct(id), 1));
else
shoppingCart[index].Quantity++;
Session["shoppingCart"] = shoppingCart;
}
return View("ShoppingCart");
}
public ActionResult Checkout()
{
OrderDetail orderDetail = wcf.GetOrderDetail();
return View();
}
}
И вот класс
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using ShoppingCartApp.ServiceReference1;
namespace ShoppingCartApp.Classes
{
public class CartItem
{
private Product product = new Product();
public Product Product
{
get { return product; }
set { product = value; }
}
private int quantity;
public int Quantity
{
get { return quantity; }
set { quantity = value; }
}
public CartItem(Product product, int quantity)
{
this.product = product;
this.Quantity = quantity;
}
}
}
Что именно он говорит мне сделать?