Neo
Neo

Reputation: 541

Not able to set cookie value

i have a method call docount()

the code

if (Request.Cookies["searchCounter"] != null)
{
    Response.Write("cookie old cookie ");
    int scvalue = int.Parse(Request.Cookies["searchCounter"].Value);
    int sc =  scvalue + 1;
    Request.Cookies["searchCounter"].Value = sc.ToString();
    Request.Cookies["searchCounter"].Expires = DateTime.Now.AddDays(2);

}
else
{
    Response.Write("new cookie ");
    Response.Cookies["searchCounter"].Value = "1";
    Response.Cookies["searchCounter"].Expires = DateTime.Now.AddDays(2);
}


Response.Write("Cookie value: " + Request.Cookies["searchCounter"].Value);

for some reason it is always hitting the else statement. any idea what i did wrong.

Upvotes: 0

Views: 522

Answers (1)

Rudy
Rudy

Reputation: 2373

It should be something like this:

if (Request.Cookies["searchCounter"] != null && Request.Cookies["searchCounter"].Value != "")
{
    // some code...
    Response.Cookies["searchCounter"].Value = "some data";
    Response.Cookies["searchCounter"].Expires = DateTime.Now.AddDays(1);
}
else
{
    Response.Cookies["searchCounter"].Value = "some data";
    Response.Cookies["searchCounter"].Expires = DateTime.Now.AddDays(1);
}

Read from Request and write to Response.

Upvotes: 2

Related Questions