Code:
(cookie.aspx)
<script runat="server"> // sử lý dự kiện click nút đăng nhập protected void bt_login_click(Object Src, EventArgs E) { if(tb_username.Text != ""){
// khai báo biến cookie HttpCookie cookie_username = new HttpCookie("username",tb_username.Text);
// Gán thời gian sống của Cookie là 30 ngày cookie_username.Expires = DateTime.Now.AddDays(30);
// Thêm Cookie Response.Cookies.Add(cookie_username);
// làm tươi Response.Redirect("cookie.aspx"); } } // sử lý dự kiện click nút Xóa Cookie protected void bt_delete_click(Object Src, EventArgs E) { // khai báo biến cookie HttpCookie cookie_username = new HttpCookie("username",""); // Gán thời gian sống của Cookie là thời gian hiện tại cookie_username.Expires = DateTime.Now; // Thêm Cookie Response.Cookies.Add(cookie_username); // làm tươi Response.Redirect("cookie.aspx"); } </script> <%@ Page Language="C#" ContentType="text/html" ResponseEncoding="utf-8" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Untitled Document</title> </head> <body> <form action="" method="post" name="form1" runat="server" id="form1"> <!–Kiểm tra nếu biến Cookie username tồn tại thì đăng nhập–> <%if(Request.Cookies["username"] == null){%> Tên đăng nhập <asp:TextBox ID="tb_username" runat="server" /> <asp:Button ID="bt_login" runat="server" OnClick="bt_login_click" Text="Đăng nhập" /> <!–Ngược lại thì hiển thị tên đăng nhập–> <%}else{%> Chào, <%=Request.Cookies["username"].Value%> <asp:Button ID="bt_delete" runat="server" OnClick="bt_delete_click" Text="Xóa Cookie" /> <%}%> </form> </body> </html>
Download :
http://www.box.net/public/1v68lyv0ec Theo Thanh Tam - forum.infoworldschool
|