在cookie中存储和检索数据

在cookie中存储和检索数据

本文介绍了在cookie中存储和检索数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨..

我在第1页有一个下拉列表。我选择了我想要的项目,然后点击go ..它将我带到下一页(第2页)并获取结果。 。当我回到第1页时,下拉列表显示默认值而不是我选择的那个。当我退出我的应用程序并登录时,同样的事情发生。我想要的是下拉列表应该显示相同的内容直到我选择的值,除非我关闭浏览器。我已经将下拉列表存储在cookie中。但是当我注销登录到我的应用程序或者当我去其他页面时,我有点担心如何填充它回到我已经给出条件的页面。这就是我所做的事情





HttpCookie myCookie = new HttpCookie(" MyTestCookie");

DateTime now = DateTime.Now;



//设置cookie值。

myCookie.Value = now.ToString();

//设置cookie过期日期。

myCookie.Expires = n ow.AddYears(50); //对于一个有效永不过期的cookie



//添加cookie。

Response.Cookies.Add(myCookie);



Response.Write("< p>已写入cookie。);





//读取饼干



HttpCookie myCookie =新的HttpCookie(MyTestCookie);

myCookie = Request.Cookies [" MyTestCookie"];



//读取cookie信息并显示它。

if(myCookie!= null )

Response.Write("< p>" + myCookie.Name +"< p>" + myCookie.Value);

else

Response.Write(未找到);

Hi..
I have a dropdownlist in page1.I select the item that I want and click on go..It takes me to the next page(page2) and gets me the result..Again when I come back to page 1 the dropdownlist shows the default value and not the one which I selected..The same thing happens when I log out of my application and logs in..all that I wanted is dropdownlist should show the same value which I selected until and unless I close the browser.i have stored the dropdownlist in cookie..But I''m bit worried how to populate it when I log out nd login to my application or when i go some other page and come back to the page where I have given the condition..this is what I have done


HttpCookie myCookie = new HttpCookie("MyTestCookie");
DateTime now = DateTime.Now;

// Set the cookie value.
myCookie.Value = now.ToString();
// Set the cookie expiration date.
myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire

// Add the cookie.
Response.Cookies.Add(myCookie);

Response.Write("<p> The cookie has been written.");


//Read cookie

HttpCookie myCookie = new HttpCookie("MyTestCookie");
myCookie = Request.Cookies["MyTestCookie"];

// Read the cookie information and display it.
if (myCookie != null)
Response.Write("<p>"+ myCookie.Name + "<p>"+ myCookie.Value);
else
Response.Write("not found");

推荐答案

HttpCookie myCookie = new HttpCookie("MyTestCookie");
 myCookie = Request.Cookies["MyTestCookie"];

 // Check for cookie already present
 if (myCookie != null)
 Response.Write("Cookie is already there.");
 else
{
//create cookie

HttpCookie myCookie = new HttpCookie("MyTestCookie");
 DateTime now = DateTime.Now;

 // Set the cookie value.
 myCookie.Value = now.ToString();
 // Set the cookie expiration date.
 myCookie.Expires = now.AddYears(50); // For a cookie to effectively never expire

 // Add the cookie.
 Response.Cookies.Add(myCookie);

 Response.Write("The cookie has been written.");
}







Ur读取cookie代码与你已经写过的相同

希望这能帮到你。




Ur reading cookie code remains same as u hav written already
hope this helps u out.


这篇关于在cookie中存储和检索数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 04:25