2016-04-30 8 views
0

私はセッションでmvc5でショッピングカートを書くが、私はcookies.Hereと実装を置き換えたいためのアクションです:Generic Listを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"); 
    } 

とItemクラスは次のとおりです。

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; 
     } 

が、私は2つのエラーだ:と 暗黙的System.Web.HttpC」にタイプ「System.Collections.Generic.List」を変換できませんがookie '
および プロパティまたはインデクサ' System.Web.HttpCookieCollection.this [string] 'を割り当てることはできません。これは読み取り専用です。

どうすればいいですか? ありがとう

+0

'HttpCookie cookie = new HttpCookie(" Cart "); cookie.Value =カート; Response.Cookies.Add(cookie); ' –

+0

@StephenMueckeまあ、私は、ユーザーが少し違って解決しようとしていて、実際にはこれをクッキーで解決しようとすると悪い方法だと思っていません。 –

+0

@VolodymyrBilyachat、 OPの質問の例外(そして私はその悪い考えに同意する) –

答えて

3

まず、オブジェクトをクッキーに保存することはできません。クッキーを受け入れる文字列であるため、まずシリアル化する必要があります。 あなたが

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

を使用することができます。しかし、クッキーに問題は、彼らがare limited

私の提案ですカートを取得するために、その後Json.Net package

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

をインストールすることであろう最も簡単な方法カートのIDとしてGuid.NewGuid()をクッキーに保存し、そのIDのデータベースにカートを保存することです。

関連する問題