创建和调用cookie

时间:2014-03-31 15:26:03

标签: c# asp.net cookies

我必须创建一个cookie,然后检索存储的cookie。

我该怎么做呢?正在存储的cookie必须包含我在“我的爱好”页面上输入的信息,该页面将显示在“摘要”页面上。

我必须保存cookie,然后重定向到Summary2并调用我按下按钮时存储的cookie。这是我到目前为止的代码,我相信与我要求的相关

 protected void btnDisplay_Click(object sender, EventArgs e)
    {
        string vacations = Session["Vacations"] as string;
        string hobbies = Session["Hobbies"] as string;
        string classes = Session["Classes"] as string;

        lblDisplay.Text = "Your favorite vacations spots are: " + vacations + "<br />" +
        "Your hobbies are: " + hobbies + "<br />" +
        "Your IT Classes are: " + classes;

    }
    protected void btnRedirect_Click(object sender, EventArgs e)
    {
        Response.Cookies["Hobbies"].Value = hobbies;
        Response.Cookies["userName"].Expires = DateTime.Now.AddDays(30);

        HttpCookie aCookie = new HttpCookie("lastVisit");
        aCookie.Value = DateTime.Now.ToString();
        aCookie.Expires = DateTime.Now.AddDays(1);
        Response.Cookies.Add(aCookie);

        Response.Redirect("Summary2.aspx", true);
    }

以下是我在Summary2页面上检索cookie的内容......

protected void btnDisplay_Click(object sender, EventArgs e)
    {
        if (Request.Cookies["userName"] != null)
            lblDisplay.Text = Server.HtmlEncode(Request.Cookies["userName"].Value);

        if (Request.Cookies["userName"] != null)
        {
            HttpCookie aCookie = Request.Cookies["userName"];
            lblDisplay.Text = Server.HtmlEncode(aCookie.Value);
        }

    }

我主要不知道如何存储在我的爱好页面中输入的信息。任何有关这方面的帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

把&#34; Cookie&#34;在您的Site.Master中,您可以在任何地方访问它。

答案 1 :(得分:0)

我弄清楚我做错了什么。我在错误的按钮命令中使用了cookie方法,在我的Summary2中,我调用了错误的cookie名称。