javascript - Cookie(使用 ASP :NET) (set with javascript) 读取

标签 javascript c# asp.net cookies

请遵循我之前在 stackoverflow 中关于讨论的帮助: Show a div in asp.net on condition

我有一个 ASP.NET 页面,其中包含 HTML 中的 Web 表单,并具有 javascript 代码集 cookie。 (我知道 javascript 正在设置 cookie,因为我可以通过 ctrl+shift+I 组合在 google chrome 中看到它们)。

我在这个解决方案背后的代码中编写了这样的代码,以便根据是否设置了cooke值来显示/不显示表单:

  protected void Page_Load(object sender, EventArgs e)
{

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

    // Read the cookie information and display it.
    if (myCookie != null)
        webform.Visible = false;
    else
        webform.Visible = true;

那是行不通的。这个显示 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");

(我将 MyTestCookie 更改为“mycookie”)

我还发布了为我的网络表单设置 cookie 的函数:

        function tempcookie() {
        days = 1; // number of days to keep the cookie
        myDate = new Date();
        myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
        document.cookie = 'cookieName=cookieclose; expires=' + myDate.toGMTString();


        function permacookie() {
        days = 30; // number of days to keep the cookie
        myDate = new Date();
        myDate.setTime(myDate.getTime() + (days * 24 * 60 * 60 * 1000));
        document.cookie = 'cookieName=cookiesignup; expires=' + myDate.toGMTString();
         }

最佳答案

我对你的代码做了一些修改。希望对您有所帮助。

HttpCookie myCookie = new HttpCookie("tempcookieforclose");
myCookie.Values.Add("date", "1");
Response.Cookies.Add(myCookie);
// Read the cookie information and display it.
myCookie = Request.Cookies["tempcookieforclose"];
if (myCookie != null)
    Response.Write("In If");
else
    Response.Write("In Else");

关于javascript - Cookie(使用 ASP :NET) (set with javascript) 读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26065319/

相关文章:

javascript - 如何正确格式化 PHP foreach 循环?

javascript - ng-show 在 ng-repeat 中使用多个过滤器

c# - Sharepoint 到 ASP.net MVC 文件下载

c# - 如何使用 Facebook App 指定 Windows 桌面平台

javascript - 如何将一个div元素的高度设置为与另一个div相同

c# - 如何使用带有 c# 的 OpenXML SDK v2.0 将新工作表添加到 Excel .xlsx 文件?

javascript - C# 中的 CustomValidator 未拾取颜色

c# - 如何在 Asp.Net 中设置上传文件的物理路径?

asp.net - 如何向 Web 方法传递参数?

javascript - 如何将旋转的子 div 居中到旋转的父 div 并坚持到父 div 的顶部?