2012-06-21 64 views
2
protected void Page_Load(object sender, EventArgs e) 
    { 
     if (!IsPostBack) 
     { 
      this.GetLeft.Value = invited.GetInviteCountByWeb().ToString(); 
      HttpCookie oldCookie = Request.Cookies["Time"]; 
      if (oldCookie != null) 
      { 
       if (DateTime.Now.ToString("yyyy-MM-dd") == Convert.ToDateTime(oldCookie.Values["GetTime"]).ToString("yyyy-MM-dd")) 
       { 
        this.IsGet.Value = "false"; 
       } 
       else 
       { 
        HttpCookie newCookie = new HttpCookie("Time"); 
        newCookie.Values.Add("GetTime", DateTime.Now.Date.ToString("yyyy-MM-dd")); 
        newCookie.Expires = DateTime.Now.AddHours(24.0); 
        Response.Cookies.Add(newCookie); 
       } 
      } 
     } 
    } 

,但它不工作时,oldcookie为空时,关闭浏览器每次.. 所以我怎样才能设置按钮点击,每天一次?C#按钮,点击每日一次

+0

你想做什么?一般来说,您不能依靠浏览器来保持持久性cookie,因为您可以告诉浏览器在浏览器关闭时删除它们。 – Paolo

+0

为什么使用可空属性'this.IsGet'?什么类封装了这个方法? –

+0

我加了ASP.NET标签来澄清。无论如何,这是一个不好的方法,你必须将信息服务器端(DB想到的)存储在cookie中。如果用户在每次关闭浏览器时自动清除cookie,该怎么办? – Alex

回答

3

你的其他陈述是在错误的地方,试着这样;

protected void Page_Load(object sender, EventArgs e) 
{ 
    if (!IsPostBack) 
    { 
     this.GetLeft.Value = invited.GetInviteCountByWeb().ToString(); 
     HttpCookie oldCookie = Request.Cookies["Time"]; 
     if (oldCookie != null) 
     { 
      if (DateTime.Now.ToString("yyyy-MM-dd") == Convert.ToDateTime(oldCookie.Values["GetTime"]).ToString("yyyy-MM-dd")) 
      { 
       this.IsGet.Value = "false"; 
      } 
     } 
     else 
     { 
      HttpCookie newCookie = new HttpCookie("Time"); 
      newCookie.Values.Add("GetTime", DateTime.Now.Date.ToString("yyyy-MM-dd")); 
      newCookie.Expires = DateTime.Now.AddHours(24.0); 
      Response.Cookies.Add(newCookie); 
     } 
    } 
+0

不工作,刷新浏览器显示var,但重新启动浏览器,oldcookie为空... –

+0

你能告诉我另一种方法,限制用户可以每天点击一次按钮吗? –