当前位置: 移动技术网 > IT编程>开发语言>.net > asp.net 购物车的实现浅析

asp.net 购物车的实现浅析

2017年12月12日  | 移动技术网IT编程  | 我要评论

香港富豪酒店招聘,狂野未婚夫,怎么制作图片

该购物车的功能如下:
. 通过ajax实现添加和删除车上的物品。
. 删除的物品会显示出来,可以重新添加到购物车。
. 嗯...没有了,具体大家接着看吧。

购物车的结构我打算用一个table来展示,在usercontrol里使用listview展现购物车的物品(因为比拼接字符串要容易维护的多)。具体代码如下(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'>
商品编号
</td>
<td>
商品名称
</td>
<td width='10%'>
京东价
</td>
<td width='8%'>
返现
</td>
<td width='8%'>
赠送积分
</td>
<td width='9%'>
商品数量
</td>
<td width='7%'>
删除商品
</td>
</tr>
<tr runat="server" id="itemplaceholder" />
<tr>
<td colspan='7' style='height: 30px'>
重量总计:<%= this.getproductsweight() %>kg   原始金额:¥307.00元 - 返现:¥0.00元<br />
<span style='font-size: 14px'><b>商品总金额(不含运费):<span id='cartbottom_price'>¥307.00</span>元</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='减一' 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='加一'
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)">
删除</a>
</td>
</tr>
</itemtemplate>
</asp:listview>

我想大家应不用我解释代码的意思了,很简单。
后台代码如下:
复制代码 代码如下:

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

把对购物车的逻辑都写到这里面,通过action来判断是什么操作,一样简单的代码。再来看看product类:
复制代码 代码如下:

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="毛毛仔妮妮熊mx9470",price="99.00",backmoney="0.00",score="0",count="1"},
new product{id="155097",name="xxxxxx新款轻巧便携式电脑桌(送鼠标垫)",price="79.00",backmoney="¥0.00",score="0",count="1"},
new product{id="155098",name="xxxxxx护眼台灯(理想)stl-t412w-03wt",price="69.00",backmoney="¥0.00",score="0",count="1"}
};
return list.where(p => { return p.id != productid; }).tolist();
}
}

接下来在shopcartdetail.aspx页面使用该usercontrol:
复制代码 代码如下:

<div id="products">
<demo:shopcarttest id="shopcarttest1" runat="server" />
</div>

通过ajax使用购物车还需要两个类:
复制代码 代码如下:

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

这两个类是参考老赵提出来的方案完成,具体原理,你可以看这里。
剩下来都是javascript了,这里我并没有使用任何类库或者框架。代码如下:
复制代码 代码如下:

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 + "');\">重新购买</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) { }
}

代码依旧很容易看懂,需要解释的就是删除的操作,分为三步:
将需要删除的物品先保存起来:setdelproduct(obj, productid);
在后台购物车清单上面将物品删除,并返回删除后的物品清单:ajaxcommon("action=removeproductonshoppingcart&productid=" + productid);
将删除的物品输出,放到已删除列表(完全在客户端操作):setdelproductshow();
还有从删除列表中将删除的物品重新添加到购物车当中,分为两步:
在后台将物品添加到物品清单(和直接添加物品调用同一个方法):addproduct
从已删除列表中将该物品删除(完全在客户端操作):readdedproduct
这样,一个基本的购物车就完成了。但是具体对于数据的操作,需要您进一步处理。本文对于数据的操作只是示例而已。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网