asp.net cookies實現購物車代碼

來源:互聯網
上載者:User

cookies的購物車類

先來看一下簡單cookie應用

在 Cookies 集合中設定屬性來寫入 Cookie
在你想要寫入 Cookie 的 ASP.NET 頁面中,在 Cookies 集合中指定 Cookie 的屬性。

如下代碼執行個體說明了一個名為 UserSettings 的 Cookie,並為子鍵 Font 和 Color 設定了值。同時也把失效時間設定成了明天。

Response.Cookies["UserSettings"]["Font"] = "Arial";
Response.Cookies["UserSettings"]["Color"] = "Blue";
Response.Cookies["UserSettings"].Expires = DateTime.Now.AddDays(1d);

建立 HttpCookie 對象的執行個體來寫入 Cookie
建立 HttpCookie 類型的一個對象執行個體並為其指定名稱。

指定 Cookie 子鍵中的值並設定 Cookie 的屬性。

把這個 Cookie 添加到 Cookies 集合中。

如下代碼執行個體說明了一個名為 myCookie 的 HttpCookie 對象執行個體,用來展示一個名為 UserSettings 的 Cookie。

HttpCookie myCookie = new HttpCookie("UserSettings");
myCookie["Font"] = "Arial";
myCookie["Color"] = "Blue";
myCookie.Expires = DateTime.Now.AddDays(1d);
Response.Cookies.Add(myCookie);

 

ASP.NET 實踐:讀取 Cookie
Cookies 提供了一種在 Web 應用程式中儲存特定使用者資訊(如記錄或使用者偏好)的方式。Cookie 是連同請求和回應一起在 Web 服務器和用戶端之間來回傳送的少量文本。Web 應用程式能夠在使用者訪問網站的時候讀取 Cookie 中所包含的資訊。

瀏覽器負責對使用者系統中的 Cookies 進行管理。Cookies 連同頁面請求一起被發送到伺服器,並作為 HttpRequest 對象中的一部分而能夠被訪問,並暴露了一個 Cookies 集合。你只能夠讀取當前域或路徑中的頁面所建立的 Cookies。


讀取 Cookie
把 Cookie 的名稱作為關鍵字從 Cookies 中讀取一個字串。

如下執行個體讀取了一個名為 UserSettings 的 Cookie,然後讀取名為 Font 的子鍵的值。

if (Request.Cookies["UserSettings"] != null)
{
    string userSettings;
    if (Request.Cookies["UserSettings"]["Font"] != null)
    { userSettings = Request.Cookies["UserSettings"]["Font"]; }
}

 

ASP.NET 實踐:刪除 Cookie
你不能直接刪除使用者電腦中的 Cookie。但是,你能夠通過把 Cookie 的有效日期設定成一個已經過去的日期來指揮使用者瀏覽器對 Cookie 進行刪除。使用者在下一次對設定在 Cookie 中的域或路徑中的頁面進行訪問的時候,瀏覽器會檢測並刪除已經到期的 Cookies。

提示:調用 Cookies 集合的 Remove 方法可以在伺服器端把 Cookie 從集合中刪除,但是 Cookie 將不會被發送到用戶端。因此,這個方法不會從用戶端刪除已經存在的 Cookie。

為 Cookie 指派一個已經過去的日期
檢測 Cookie 是否存在,如果存在,建立一個擁有相同名稱的新 Cookie。

把新 Cookie 的有效日期設定成一個已經過去的時間。

把這個新 Cookie 添加到 Cookies 集合對象中。

如下代碼執行個體說明了如何為 Cookie 設定一個已經過去的日期。

if (Request.Cookies["UserSettings"] != null)
{
    HttpCookie myCookie = new HttpCookie("UserSettings");
    myCookie.Expires = DateTime.Now.AddDays(-1d);
    Response.Cookies.Add(myCookie);
}

 


再看詳細的購物車執行個體

using System;
    using System.Data;
    using System.Configuration;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;
    //文章來源:http://www.111cn.net
    public class CookieShoppingCart
    {
    ///
    /// 加入購物車
    ///
    ///
    ///
    public static void AddToShoppingCart(int ProductID, int Quantity, int Box)
    {
    if (HttpContext.Current.Request.Cookies["ShoppingCart"] == null)
    {
    HttpCookie oCookie = new HttpCookie("ShoppingCart");
    //Set Cookie to expire in 3 hours
    oCookie.Expires = DateTime.Now.AddYears(3);
    oCookie.Value = ProductID.ToString() + ":" + Quantity.ToString() + ":" + Box.ToString();
    HttpContext.Current.Response.Cookies.Add(oCookie);
    }
    //如果cookie已經存在
    else
    {
    bool bExists = false;
    HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];
    oCookie.Expires = DateTime.Now.AddYears(3);
    string ShoppingCartStr = oCookie.Value.ToString();
    string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });
    //查看cookie中是否有該產品
    string newCookie = "";
    for (int i = 0; i < arrCookie.Length; i++)
    {
    if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) == ProductID.ToString().Trim())
    {
    bExists = true;
    string OldQuantity = arrCookie[i].Trim().Substring(arrCookie[i].Trim().IndexOf(':') + 1);//得到數量
    OldQuantity = OldQuantity.Remove(OldQuantity.LastIndexOf(":"));
    OldQuantity = (Convert.ToInt32(OldQuantity) + Quantity).ToString();
    arrCookie[i] = arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) + ":" + OldQuantity + ":" + Box.ToString();
    //HttpContext.Current.Response.Write(arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) + "已存在!數量:" + OldQuantity + "
    ");
    //HttpContext.Current.Response.Write(arrCookie[i] + "
    ");
    }
    newCookie = newCookie + "," + arrCookie[i];
    }
    //如果沒有該產品
    if (!bExists)
    {
    oCookie.Value = oCookie.Value + "," + ProductID.ToString() + ":" + Quantity.ToString() + ":" + Box.ToString();
    }
    else
    {
    oCookie.Value = newCookie.Substring(1);
    }
    HttpContext.Current.Response.Cookies.Add(oCookie);
    HttpContext.Current.Response.Write("ShoppingCart:" + HttpContext.Current.Request.Cookies["ShoppingCart"].Value);
    }
    }
///
    /// 移除購物車子項
    ///
    ///
    public static void RemoveShoppingCart(int ProductID)
    {
    if (HttpContext.Current.Request.Cookies["ShoppingCart"] != null)
    {
    HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];
    oCookie.Expires = DateTime.Now.AddYears(3);
    //Check if Cookie already contain same item
    string ShoppingCartStr = oCookie.Value.ToString();
    string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });
    string[] arrCookie2 = new string[arrCookie.Length - 1];
    int j = 0;
    string NewStr = "";
    for (int i = 0; i < arrCookie.Length; i++)
    {
    if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) != ProductID.ToString())
    NewStr = NewStr + "," + arrCookie[i];
    }
    if (NewStr == "")
    HttpContext.Current.Response.Cookies["ShoppingCart"].Value = "";
    else
    HttpContext.Current.Response.Cookies["ShoppingCart"].Value = NewStr.Substring(1);
    }
    }
    public static void UpdateShoppingCart(int ProductID, int Quantity, bool box)
    {
    int Box = 1;
    if (!box)
    Box = 0;
    if (HttpContext.Current.Request.Cookies["ShoppingCart"] != null)
    {
    bool bExists = false;
    HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];
    oCookie.Expires = DateTime.Now.AddYears(3);
    string ShoppingCartStr = oCookie.Value.ToString();
    string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });
    //查看cookie中是否有該產品
    string newCookie = "";
    for (int i = 0; i < arrCookie.Length; i++)
    {
    if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) == ProductID.ToString().Trim())
    arrCookie[i] = arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) + ":" + Quantity.ToString() + ":" + Box.ToString();
    newCookie = newCookie + "," + arrCookie[i];
    }
    HttpContext.Current.Response.Cookies["ShoppingCart"].Value = newCookie.Substring(1);
    }
    }
    public static DataTable GetShoppingCart()
    {
    DataTable dt = new DataTable();
    if (HttpContext.Current.Request.Cookies["ShoppingCart"] != null && HttpContext.Current.Request.Cookies["ShoppingCart"].Value.Trim() != "")
    {
    HttpCookie oCookie = (HttpCookie)HttpContext.Current.Request.Cookies["ShoppingCart"];
    oCookie.Expires = DateTime.Now.AddYears(3);
    string ShoppingCartStr = oCookie.Value.ToString();
    //HttpContext.Current.Response.Write(ShoppingCartStr);
    string[] arrCookie = ShoppingCartStr.Split(new char[] { ',' });
    //查看cookie中是否有該產品
    string newCookie = "";
    for (int i = 0; i < arrCookie.Length; i++)
    {
    newCookie = newCookie + "," + arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':'));
    }
    newCookie = newCookie.Substring(1);
    dt = Product.GetProductByProductIds(newCookie, -1);
    dt.Columns.Add("Quantity");
    dt.Columns.Add("Box");
    foreach (DataRow row in dt.Rows)
    {
    for (int i = 0; i < arrCookie.Length; i++)
    {
    if (arrCookie[i].Trim().Remove(arrCookie[i].IndexOf(':')) == row["ProductId"].ToString())
    {
    row["Quantity"] = arrCookie[i].Substring(arrCookie[i].IndexOf(":") + 1);
    row["Quantity"] = row["Quantity"].ToString().Remove(row["Quantity"].ToString().IndexOf(":"));
    string Box = arrCookie[i].Substring(arrCookie[i].LastIndexOf(":") + 1);
    if (Box == "1")
    row["Box"] = true;
    else
    row["Box"] = false;
    }
    }
    }
    }
    else
    {
    dt = Database.GetDataTable("select top 0 * from View_ProductList");
    dt.Columns.Add("Quantity");
    }
    return dt;
    }
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.