读书人

ASP.net用Session做购物车的有关问题

发布时间: 2013-11-06 16:26:37 作者: rapoo

ASP.net用Session做购物车的问题
用二位数组储存购物商品和价格两个信息储存在Session中,在商品页面点加入购物车,商品成功加入 但是点其他商品加入购物车以后数组就会清空永远只有一个信息,请问问题出在那?

public partial class _Default : System.Web.UI.Page
{
SqlDataReader sdr;

string[,] ary = new string[50, 2];
protected void Page_Load(object sender, EventArgs e)
{

Session.Timeout = 6000;
sltpdinfo();
}
protected void sltpdinfo()
{

SqlConnection scn = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename='d:\\My Documents\\Visual Studio 2005\\WebSites\\b2cweb\\App_Data\\b2cdatabase.mdf';Integrated Security=True;User Instance=True");
SqlCommand sltpd = new SqlCommand("select pcode,pname,pscprice from product where pcode=@pcode",scn);
scn.Open();
SqlParameter pcode = new SqlParameter("pcode",Request.QueryString["pcode"]);
sltpd.Parameters.Add(pcode);
sdr = sltpd.ExecuteReader();
sdr.Read();

}
protected void btnpay_Click(object sender, EventArgs e)
{

}
protected void btnadd_Click(object sender, EventArgs e)
{

string[,] ary = new string[50, 2];
Session["pcode"] = sdr[0];
Session["pname"] = sdr[1];
Session["pscprice"] = sdr[2];
Session["mycar"] = ary;
if (ary[0,0]==null)
{
ary[0,0] = Session["pname"].ToString();
ary[0,1] = Session["pscprice"].ToString();
}
else
{
for (int i = 0; i < 50; i++)
{
if (ary[i, 0] == Session["pname"].ToString())
{
ary[i + 1, 0] = Session["pname"].ToString();
ary[i + 1, 1] = Session["pscprice"].ToString();
}
}
}

Response.Redirect("~/shopcar.aspx");
}
}

[解决办法]
一般这样工作量太大,我们只用SessionID来做购物车的临时ID就可以了,记录还在放到数据库中
[解决办法]
string[,] ary = new string[50, 2];

你每次都建个空数组

string[,] ary;
if(Session["mycar"]!=null)
{
ary = Session["mycar"] as string[,];
}
else
{
ary = new string[50, 2];
}


*****************************************************************************
签名档: http://feiyun0112.cnblogs.com/
[解决办法]
string[,] ary = new string[50, 2];每次都是新数组。应该已追加的方式写入sesson
另外,购物车半小时就没了,为什么不用cooike或者数据库来存储购物车?
[解决办法]
把整个数组放到Session里,Session["Cart"]=ary;string[,] ary = Session["Cart"] as string[,];
要不每次都是建一个空数组,然后把你点击的那件商品id放到数据的第一项。

读书人网 >asp.net

热点推荐