A brief analysis of the implementation of asp. net shopping cart

  • 2020-05-10 18:02:49
  • OfStack

The shopping cart functions as follows:
Add and remove items from the vehicle through ajax.
Deleted items are displayed and can be re-added to the shopping cart.
. Um... No more, you'll see.

I'm going to show the structure of the shopping cart with an table, and use ListView in UserControl to show the items in the shopping cart (because it's much easier to maintain than concatenating strings). The specific code is as follows (ShopCartTest.ascx) :
 
<asp:ListView ID="ListView1" runat="server"> 
<LayoutTemplate> 
<table runat="server" cellpadding='0' cellspacing='0' width='100%'> 
<tr> 
<td width='7%' style='height: 30px'> 
 Product id  
</td> 
<td> 
 Name of commodity  
</td> 
<td width='10%'> 
 Jingdong price  
</td> 
<td width='8%'> 
 Cash back  
</td> 
<td width='8%'> 
 Present integral  
</td> 
<td width='9%'> 
 The number  
</td> 
<td width='7%'> 
 Delete the goods  
</td> 
</tr> 
<tr runat="server" id="itemPlaceholder" /> 
<tr> 
<td colspan='7' style='height: 30px'> 
 Total weight: <%= this.GetProductsWeight() %>kg    Original amount:  RMB  307.00 yuan  -  Cashback: RMB 0.00 yuan <br /> 
<span style='font-size: 14px'><b> Total amount of goods ( Excluding freight costs ) : <span id='cartBottom_price'> RMB 307.00</span> yuan </b></span> 
</td> 
</tr> 
</table> 
</LayoutTemplate> 
<ItemTemplate> 
<tr> 
<td style='padding: 5px 0 5px 0;'> 
<%#(Container.DataItem as Product).ID %> 
</td> 
<td> 
<a target='_blank' href='http://www.xxx.com/product/<%#(Container.DataItem as Product).ID %>.html'> 
<%#(Container.DataItem as Product).Name %></a> 
</td> 
<td> 
<span> 
<%#(Container.DataItem as Product).Price %></span> 
</td> 
<td> 
<%#(Container.DataItem as Product).BackMoney %> 
</td> 
<td> 
<%#(Container.DataItem as Product).Score %> 
</td> 
<td> 
<a href='#none' title=' Reduction of 1' onclick="changeCount('-','<%#(Container.DataItem as Product).ID %>','sku');" 
style='text-decoration: none'>-</a><input type='text' id='txt<%#(Container.DataItem as Product).ID %>' 
name='txtChange<%#(Container.DataItem as Product).ID %>' maxlength='4' style='width: 30px' 
value='<%#(Container.DataItem as Product).Count %>' /><a href='#none' title=' add 1' 
onclick="changeCount('+','<%#(Container.DataItem as Product).ID %>');" style='text-decoration: none'>+</a> 
</td> 
<td> 
<a href='#none' id='btn_del_173259' onclick="removeProductOnShoppingCart('<%#(Container.DataItem as Product).ID %>',this)"> 
 delete </a> 
</td> 
</tr> 
</ItemTemplate> 
</asp:ListView> 

I don't think you need me to explain what the code means. It's very simple.
The background code is as follows:
 
public partial class ShopCartTest : System.Web.UI.UserControl 
{ 
List<Product> productsList = null; 
protected override void OnPreRender(EventArgs e) 
{ 
base.OnPreRender(e); 
switch (Acion) 
{ 
case "removeProductOnShoppingCart": 
productsList = Product.GetProductsInCart(ProductID); 
break; 
case "changeProductCount": 
productsList = Product.GetProductsInCart(null); 
foreach (var item in productsList) 
{ 
if (item.ID == ProductID) 
{ 
item.Count = "3"; 
} 
} 
break; 
case "AddProduct": 
productsList = Product.GetProductsInCart(null); 
productsList.Add(new Product() { ID = "173233", Name = "ElandMX9470", Price = "399.00", BackMoney = "0.00", Score = "0", Count = "1" }); 
break; 
default: 
productsList = Product.GetProductsInCart(ProductID); 
break; 
} 
ListView1.DataSource = productsList; 
ListView1.DataBind(); 
} 
public string GetProductsWeight() 
{ 
return Product.GetProductsInCart(ProductID).Sum(p => decimal.Parse(p.Price) * decimal.Parse(p.Count)).ToString(); 
} 
public string GetProductsOriginalPrice() 
{ 
return Product.GetProductsInCart(ProductID).Sum(p => decimal.Parse(p.Price) * decimal.Parse(p.Count)).ToString(); 
} 
public string ProductID { get; set; } 
public string Acion { get; set; } 
} 

Write the logic for the shopping cart here, and use action to figure out what the operation is, a simple code. Let's look at the Product class again:
 
public class Product 
{ 
public string ID { get; set; } 
public string Name { get; set; } 
public string Price { get; set; } 
public string BackMoney { get; set; } 
public string Score { get; set; } 
public string Count { get; set; } 

public static List<Product> GetProductsInCart(string productID) 
{ 
List<Product> list = new List<Product>() 
{ 
new Product{ID="173259",Name=" Fluffy baby nini bear MX9470",Price="99.00",BackMoney="0.00",Score="0",Count="1"}, 
new Product{ID="155097",Name="xxxxxx New light and portable computer table (mouse pad) ",Price="79.00",BackMoney=" RMB 0.00",Score="0",Count="1"}, 
new Product{ID="155098",Name="xxxxxx Eye lamp (ideal) STL-T412W-03WT",Price="69.00",BackMoney=" RMB 0.00",Score="0",Count="1"} 
}; 
return list.Where(p => { return p.ID != productID; }).ToList(); 
} 
} 

Next use the UserControl on the ShopCartDetail.aspx page:
 
<div id="products"> 
<demo:ShopCartTest ID="ShopCartTest1" runat="server" /> 
</div> 

Using a shopping cart through ajax requires two more classes:
 
public class GetProducts : IHttpHandler 
{ 
public void ProcessRequest(HttpContext context) 
{ 
context.Response.ContentType = "text/plain"; 
ViewManager<ShopCartTest> viewManager = new ViewManager<ShopCartTest>(); 
ShopCartTest control = viewManager.LoadViewControl("~/ShopCartTest.ascx"); 
control.ProductID = context.Request.QueryString["productId"]; 
control.Acion = context.Request.QueryString["action"]; 
context.Response.Write(viewManager.RenderView(control)); 
} 
public bool IsReusable 
{ 
get 
{ 
return false; 
} 
} 
} 

 
public class ViewManager<T> where T : UserControl 
{ 
private Page m_pageHolder; 
public T LoadViewControl(string path) 
{ 
m_pageHolder = new Page(); 
return this.m_pageHolder.LoadControl(path) as T; 
} 
public string RenderView(T control) 
{ 
StringWriter output = new StringWriter(); 
this.m_pageHolder.Controls.Add(control); 
HttpContext.Current.Server.Execute(this.m_pageHolder, output, false); 
return output.ToString(); 
} 
} 

These two classes are completed according to the scheme put forward by Lao zhao. You can see the specific principle here.
The rest is javascript, and I'm not using any libraries or frameworks here. The code is as follows:
 
function ajaxCommon(requst) { 
2 var xmlHttp = false; 
3 if (window.ActiveXObject) { 
4 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
5 } 
6 else { 
7 if (window.XMLHttpRequest) { 
8 xmlHttp = new XMLHttpRequest(); 
9 } 
} 
xmlHttp.onreadystatechange = function() { getAjaxValue(xmlHttp) } 
xmlHttp.open("GET", "/GetProducts.ashx" + '?roid=' + Math.random() + '&' + requst); 
xmlHttp.send(null); 
} 
function getAjaxValue(xmlHttp) { 
if (xmlHttp.readyState == 4) { 
if (xmlHttp.status == 200) { 
document.getElementById("products").innerHTML = xmlHttp.responseText; 
} 
} 
} 
function addProduct(productID, productCount) { 
ajaxCommon("action=AddProduct&productId=" + productID + "&productCount=" + productCount); 
} 
function removeProductOnShoppingCart(productId, obj) { 
debugger; 
setDelProduct(obj, productId); 
ajaxCommon("action=removeProductOnShoppingCart&productId=" + productId); 
setDelProductShow(); 
} 
function changeCount(type, productID) { 
var changeCount = 0; 
var txtCount = 0; 
if (type == "-") { 
changeCount = -1; 
} 
if (type == "+") { 
changeCount = 1; 
} 
txtCount = document.getElementById("txt" + productID).value; 
ajaxCommon("action=changeProductCount&productId=" + productID + "&productCount=" + txtCount); 
} 
function DeledProductInfo() { 
this.ID = ''; 
this.Name = ''; 
this.Price = ''; 
this.Count = ''; 
} 
var delProduct = null; 
function setDelProduct(obj, productID) { 
try { 
delProduct = new DeledProductInfo(); 
var trObj = obj.parentNode.parentNode; 
delProduct.ID = trObj.cells[0].innerHTML; 
delProduct.Name = trObj.cells[1].innerHTML; 
delProduct.Price = trObj.cells[2].innerHTML; 
delProduct.Count = document.getElementById('txt' + productID).value; 
} catch (e) { } 
} 
function setDelProductShow() { 
try { 
if (document.getElementById('divDeledProduct') == null) return; 
if (delProduct != null && delProduct.ID != '') { 
var dHtml = "<table><tr>"; 
dHtml += "<td style='width:70px'>" + delProduct.ID + "</td>"; 
dHtml += "<td style='text-align:left'>" + delProduct.Name + "</td>"; 
dHtml += "<td>" + delProduct.Price + "</td>"; 
dHtml += "<td>" + delProduct.Count + "</td>"; 
dHtml += "<td><a href='#none' onclick=\"addProduct('" + delProduct.ID + "','" + delProduct.Count + "');reAddedProduct('delProduct" + delProduct.ID + "');\"> To buy </a></td>"; 
dHtml += "</tr></table>"; 
document.getElementById('divDeledProduct').style.display = ''; 
document.getElementById('divDeledProduct').innerHTML += "<div id='delProduct" + delProduct.ID + "'>" + dHtml + "</div>"; 
} 
delProduct = null; 
} catch (e) { } 
} 
function reAddedProduct(reAddDivId) { 
try { 
debugger; 
document.getElementById('divDeledProduct').removeChild(document.getElementById(reAddDivId)); 
if (document.getElementById('divDeledProduct').childNodes.length == 0) { 
document.getElementById('divDeledProduct').style.display = 'none'; 
} 
} catch (e) { } 
} 

The code is still easy to understand. What needs to be explained is the operation of deletion, which is divided into three steps:
Save the items that need to be deleted: setDelProduct(obj, productId);
Delete the item on the background shopping cart list and return the deleted item list: ajaxCommon("action=removeProductOnShoppingCart&productId=" + productId);
Output the deleted items to the deleted list (completely on the client side) : setDelProductShow();
There are also two steps to re-add the deleted item from the delete list to the shopping cart:
Adding an item to the item list in the background (the same method as adding an item directly) : addProduct
Remove the item from the deleted list (completely on the client side) : reAddedProduct
This completes a basic shopping cart. But the specific operation of the data, you need to step 1 processing. This article's manipulation of the data is just an example.

Related articles: