asp.netはjsを通じてCookieの作成とCookie配列をクリアするコードを実現します.

3267 ワード

 
  


<br>protected void Button1_Click(object sender, EventArgs e) <br>{ <br>HttpCookie cookie = Request.Cookies["MyCook"]; <br>// <br>if (cookie == null) <br>{ <br>cookie = new HttpCookie("MyCook"); // Cookie <br>DateTime dt = DateTime.Now; <br>TimeSpan ts = new TimeSpan(0, 0, 10, 0, 0); <br>cookie.Expires = dt.Add(ts); <br>Response.AppendCookie(cookie); <br>} <br>// 5 checkBox, checkBox cookie <br>for (int i = 1; i < 6; i++) <br>{ <br>CheckBox control = this.FindControl(String.Format("CheckBox{0}", i)) as CheckBox; <br>if (control == null) continue; <br>string key = String.Format("Num{0}", i); <br>string value = control.Checked.ToString(); <br>cookie.Values[key] = value; <br>} <br>// <br>foreach (string key in cookie.Values.AllKeys) <br>{ <br>string value = cookie.Values[key]; <br>Response.Write(String.Format("SubKey:{0};  SubValue:{1}<br />", key, value)); <br>} <br>} <br>



<br>function ClearCookie() { <br>var exp = new Date(); <br>exp.setTime(exp.getTime() - 1); <br>var a = GetCookie('MyCook'); <br>alert(a); <br>var b = name + "=" + a + "; expires=" + exp.toString(); <br>document.cookie = b; <br>alert(b); <br>} <br>function GetCookie(name) <br>// Cookie <br>{ <br>var arg = name + "="; <br>var alen = arg.length; <br>var clen = document.cookie.length; <br>alert(document.cookie); <br>var i = 0; <br>while (i < clen) { <br>var j = i + alen; <br>if (document.cookie.substring(i, j) == arg) <br>return GetCookieVal(j); <br>i = document.cookie.indexOf(" ", i) + 1; <br>if (i == 0) break; <br>} <br>return null; <br>} <br>function GetCookieVal(offset) { // offset cookie <br>var endstr = document.cookie.indexOf(";", offset); <br>if (endstr == -1) <br>endstr = document.cookie.length; <br>return unescape(document.cookie.substring(offset, endstr)); <br>} <br>