Search code examples
c#asp.netcookieshttpcookie

asp.net cookie reading does not functioning (same page)


I have a single page with a button and a textbox. I was expecting that previous cookie should be read on page load. just attempting read/write simple example. button should save to cookie the textbox value. and at next opening it should read it. but mycookie is always null. what is wrong with the codes ? any clue? (thanks)

    protected void Page_Load(object sender, EventArgs e)
    {


            HttpCookie mycookie = Request.Cookies["info"];

        if(mycookie!=null)
        TextBox1.Text=mycookie["mytext"];

    }

    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        HttpCookie mycookie= new HttpCookie("info");
        mycookie.Expires = DateTime.Now.AddDays(3);

        mycookie["mytext"]=TextBox1.Text;


        Response.Cookies.Add(mycookie);
    }

Solution

  • You should probably use the Value property. Try this:

        protected void Page_Load(object sender, EventArgs e)
    {
    
    
            HttpCookie mycookie = Request.Cookies["info"];
    
        if(mycookie!=null)
        TextBox1.Text=mycookie.Value;
    
    }
    
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        HttpCookie mycookie= new HttpCookie("info");
        mycookie.Expires = DateTime.Now.AddDays(3);
    
        mycookie.Value=TextBox1.Text;
    
    
        Response.Cookies.Add(mycookie);
    }