必需了解的:實例需要做的是Cookie對象的創建和對Cookie對象數據的讀取,通過Response對象的Cookies屬性創建Cookie,通過Request對象的Cookies可以讀取Cookie對象的數據。

案例思路:創建並保存Cookie在TextBox里一定時間
login.aspx:
1 <%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %>
2
3 <!DOCTYPE html>
4
5 <html xmlns="http://www.w3.org/1999/xhtml">
6 <head runat="server">
7 <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
8 <title>登錄時記住用戶名和密碼</title>
9 </head>
10 <body>
11 <form id="form1" runat="server">
12 <div>
13 用戶名<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
14 密 碼<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br/>
15 <asp:CheckBox ID="CheckBox1" runat="server" />記住用戶名和密碼<br />
16 <asp:Button ID="Button1" runat="server" Text="登錄" OnClick="Button1_Click" />
17 <asp:Button ID="Button2" runat="server" Text="重置" OnClick="Button2_Click1"/>
18 </div>
19 </form>
20 </body>
21 </html>
login.aspx.cs:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Web;
5 using System.Web.UI;
6 using System.Web.UI.WebControls;
7
8 public partial class login : System.Web.UI.Page
9 {
10 //頁面加載時執行的內容 Start
11 protected void Page_Load(object sender, EventArgs e)
12 {
13 //第一次加載不滿足條件,之后均滿足(除Cookie到時間了),將Cookie數據輸出到TextBox里
14 if(Request.Cookies["username"]!=null&&Request.Cookies["password"]!=null)
15 {
16 TextBox1.Text = Request.Cookies["username"].Value.ToString();
17 TextBox2.Text = Request.Cookies["password"].Value.ToString();
18 }
19 }
20 //頁面加載時執行的內容 End
21 //重置按鈕的功能的實現 Start
22 protected void Button2_Click1(object sender, EventArgs e)
23 {
24 this.FindButton(this);
25 }
26 private void FindButton(Control c)
27 {
28 if (c.Controls != null)
29 {
30 foreach (Control x in c.Controls)
31 {
32 if (x is System.Web.UI.WebControls.TextBox)
33 {
34 ((System.Web.UI.WebControls.TextBox)x).Text = "";
35 }
36 FindButton(x);
37 }
38 }
39 }
40 //重置按鈕的功能的實現 End
41 //登錄按鈕的功能的實現 Satrt
42 protected void Button1_Click(object sender, EventArgs e)
43 {
44 if (CheckBox1.Checked)
45 {
46 //創建Cookie對象,保存Cookie數據,設置Cookie保存時間
47 Response.Cookies["username"].Value = TextBox1.Text;
48 Response.Cookies["username"].Expires = DateTime.Now.AddSeconds(10);
49 Response.Cookies["password"].Value = TextBox2.Text;
50 Response.Cookies["password"].Expires = DateTime.Now.AddSeconds(10);
51 Response.Redirect("Test.aspx");
52 }
53 }
54 //登錄按鈕的功能的實現 End
55 }
文章系筆者原創,轉載請注明出處,感謝合作!