日期:2014-05-17  浏览次数:20539 次

初学者提问,关于cookie
是这样的,写了个模仿京东购物车的程序,我写了两个页面,第一个页面设置了六个复选框,通过第一个页面的加入购物车的click事件把那些勾选的加入cookie,然后转到第二个页面,通过第二个页面输出,现在只是个初步,但发现第二个页面无法读处cookie,希望各位大神帮帮初学者,谢谢!代码如下。
第一页的代码
C# code
public partial class broswer : System.Web.UI.Page
{
    protected void Button1_Click1(object sender, EventArgs e)
    {
        HttpCookie cookie = new HttpCookie("things");
        cookie.Expires = DateTime.Now.AddMinutes(10.0);
        int i = 1;
        CheckBox box = new CheckBox();
        for (i = 0; i < 6; i++)
        {
            int temp = i;
            box = (CheckBox)Form.FindControl("CheckBox" + (temp + 1).ToString());
            if (box != null && box.Checked == true)
            {
                cookie.Values["ID"+temp.ToString()] = box.ID;
                cookie.Values["name"+temp.ToString()] = box.Text;
                Response.Cookies.Add(cookie);
            }
        }
        Response.Write("<script>alert('已将所选加入购物车')</script>");
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("index.aspx");
    }
}

第二页代码
C# code
public partial class index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int i=1;
        HttpCookie getCookie = Response.Cookies["things"];
        while(getCookie.Values["name"+i.ToString()]!=null)
        {
            Label1.Text = getCookie.Values["name" + i.ToString()].ToString();
            Label2.Text = getCookie.Values["ID" + i.ToString()].ToString();
            i++;
        }
    }
}


------解决方案--------------------
C# code

public partial class index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        int i=1;
        HttpCookie getCookie = Response.Cookies["things"];//Request.Cookies["things"];
        while(getCookie.Values["name"+i.ToString()]!=null)
        {
            Label1.Text = getCookie.Values["name" + i.ToString()].ToString();
            Label2.Text = getCookie.Values["ID" + i.ToString()].ToString();
            i++;
        }
    }
}

------解决方案--------------------
楼上正解。

获取cookie用Request