Asp.net cookies implement shopping cart code

Source: Internet
Author: User
Tags datetime httpcontext set cookie tostring trim

Shopping cart of cookies

Let's take a look at the simple cookie application.

Set attributes in the Cookies set to write Cookies
On the ASP. NET page where you want to write a Cookie, specify the Cookie attribute in the Cookie set.

The following code illustrates a Cookie named UserSettings and sets values for the sub-keys Font and Color. In addition, the expiration time is set to tomorrow.

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

Create an instance of the HttpCookie object to write the Cookie
Create an object instance of the HttpCookie type and specify its name.

Specify the value in the Cookie subkey and set the Cookie attributes.

Add this Cookie to the Cookies set.

The following code illustrates an HttpCookie object instance named myCookie, which is used to display a Cookie named UserSettings.

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

 

ASP. NET practice: read cookies
Cookies provide a way to store specific user information (such as historical records or user preferences) in Web applications. Cookie is a small amount of text sent back and forth between the Web server and the client together with the request and response. Web applications can read the information contained in cookies when users access websites.

The browser manages Cookies in the user system. Cookies are sent to the server together with page requests and can be accessed as part of the HttpRequest object, and a set of Cookies is exposed. You can only read Cookies created on pages in the current domain or path.


Read Cookie
Use the Cookie name as a keyword to read a string from Cookies.

The following instance reads a Cookie named UserSettings and then reads the value of the sub-key named Font.

If (Request. Cookies ["UserSettings"]! = Null)
{
String userSettings;
If (Request. Cookies ["UserSettings"] ["Font"]! = Null)
{UserSettings = Request. Cookies ["UserSettings"] ["Font"];}
}

 

ASP. NET practice: delete cookies
You cannot directly delete cookies from your computer. However, you can set the Cookie effective date to a date that has passed to direct the user's browser to delete the Cookie. When you access the page in the domain or path set in the Cookie next time, the browser detects and deletes expired Cookies.

Tip: The Remove method of the Cookie set can be called to delete the Cookie from the set on the server side, but the Cookie will not be sent to the client. Therefore, this method does not delete existing cookies from the client.

Specify an existing date for the Cookie.
Checks whether a Cookie exists. If yes, create a new Cookie with the same name.

Set the effective date of the new Cookie to a time that has passed.

Add the new Cookie to the Cookie set object.

The following code illustrates how to set an expiration date for a Cookie.

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

 


Let's look at the detailed shopping cart instance.

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;
// Source: http://www.111cn.net
Public class CookieShoppingCart
    {
///
/// Add to shopping cart
///
///
///
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 );
    }
// If the cookie already exists
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 [] {','});
// Check whether the product exists in the 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); // Obtain the quantity
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 (':') + "already exists! Quantity: "+ OldQuantity +"
");
// HttpContext. Current. Response. Write (arrCookie [I] +"
");
    }
NewCookie = newCookie + "," + arrCookie [I];
    }
// If this product does not exist
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 );
    }
    }
///
/// Remove the subitem of the shopping cart
///
///
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 [] {','});
// Check whether the product exists in the 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 [] {','});
// Check whether the product exists in the 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;
    }
    }

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.