2016-04-30 57 views
0

我寫在會議mvc5購物車,但我想用cookies.Here替換實現順序動作:如何將通用列表保存到C#中的HttpCookie中?

public ActionResult OrderNow(int id) 
    { 
     if(Session["cart"]==null) 
     { 
      List<Item> cart = new List<Item>(); 
      cart.Add(new Item(de.Products.Find(id),1)); 
      Session["cart"] = cart; 
     } 
     else 
     { 
      List<Item> cart = (List<Item>)Session["cart"]; 
      int index = isExisting(id); 
      if (index == -1) 
       cart.Add(new Item(de.Products.Find(id), 1)); 
      else 
       cart[index].Quantity++; 
      Session["cart"] = cart; 
     } 
     return View("Cart"); 
    } 

和項目類:

public class Item 
{ 
    private Product pr = new Product(); 

    public Product Pr 
    { 
     get { return pr; } 
     set { pr = value; } 
    } 


    private int quantity; 

    public int Quantity 
    { 
     get { return quantity; } 
     set { quantity = value; } 
    } 
    public Item(Product product, int quantity) 
    { 
     this.pr = product; 
     this.quantity = quantity; 
    } 
} 

我更換,如果塊搭配:

if(Request.Cookies["cart"]==null) 
     { 
      List<Item> cart = new List<Item>(); 
      cart.Add(new Item(de.Products.Find(id),1)); 
      Request.Cookies["cart"] = cart; 
     } 

但我得到了兩個錯誤: 無法隱式轉換類型「System.Collections.Generic.List」到「System.Web.HttpC ookie'
和 屬性或索引器'System.Web.HttpCookieCollection.this [string]'不能分配給 - 它是隻讀的。

我該怎麼辦? 謝謝

+0

'HttpCookie cookie = new HttpCookie(「Cart」); cookie.Value = cart; Response.Cookies.Add(cookie);' –

+0

@StephenMuecke好吧,我不認爲它的重複,因爲問題,用戶試圖解決它有點不同,實際上解決這個cookie是一種不好的方法做 –

+0

@VolodymyrBilyachat,該騙局解決這兩個在OP的問題中的例外(我同意它的一個壞主意) –

回答

3

首先,你不能保存對象到cookie,你必須序列化它,因爲cookie接受字符串。 最簡單的方法是安裝Json.Net package

Response.Cookies.Add(new HttpCookie("cart", JsonConvert.SerializeObject(cart))); 

然後讓車可以用

var cart = JsonConvert.DeserializeObject<List<Item>>(Request.Cookies["cart"]) 

但與cookies問題是他們are limited

我的建議會將Guid.NewGuid()作爲購物車ID存儲在Cookie中,然後將您的購物車存儲在具有該ID的數據庫中。

相關問題