程序中保存状态的方式之Cookies
生活随笔
收集整理的這篇文章主要介紹了
程序中保存状态的方式之Cookies
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
程序中保存狀態的方式之 Cookies,之前寫過一篇關于ViewState的。現在繼續總結Cookies方式的
新建的測試頁面login
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Login.aspx.cs" Inherits="Login" %><!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 runat="server"><title></title><script type="text/javascript">function checkSubmit() {var user = document.getElementById("txtName");var reg = /^\s*$/;if (reg.test(user.value)) {alert("請輸入用戶名!");user.focus();return false;}var pwd = document.getElementById("txtPwd");if (reg.test(pwd.value)) {alert("請輸入密碼!");pwd.focus();return false;}return true;}</script> </head> <body><form id="form1" runat="server">登錄名:<asp:TextBox ID="txtName" runat="server"></asp:TextBox>密碼:<asp:TextBox ID="txtPwd" runat="server"></asp:TextBox><asp:Button ID="btn_login" runat="server" Text="登錄" οnclick="btn_login_Click" OnClientClick="return checkSubmit()"/></form> </body> </html> login.aspx后臺.cs文件
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data;public partial class Login : System.Web.UI.Page {protected void Page_Load(object sender, EventArgs e){}protected void btn_login_Click(object sender, EventArgs e){string name = txtName.Text.Trim();string pwd = txtPwd.Text.Trim();if (name == string.Empty){MessageBox.Show(this, "請輸入用戶名!");return;}if (pwd == string.Empty){MessageBox.Show(this, "請輸入密碼!");return;}if (name == "test" && pwd == "123456"){Response.Cookies.Add(new HttpCookie("comID", "100"));Response.Cookies["comID"].Expires = DateTime.Now.AddDays(30);//設置過期時間,30天Response.Redirect("獲取cookies.aspx");}else {MessageBox.Show(this,"用戶名密碼錯誤!");}}}獲取cookies.aspx頁面后臺
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data;public partial class 獲取cookies : System.Web.UI.Page {public string comid = "";protected void Page_Load(object sender, EventArgs e){if (Request.Cookies["comID"] != null && Request.Cookies["comID"].Value != ""){comid = Request.Cookies["comID"].Value;//獲取存入的comid }MessageBox.Show(this, "登錄id=" + comid);} }刪除Cookies
Response.Cookies[CountAdmin].Expires = DateTime.Now.AddDays(-1);//刪除cookie
我登錄的時候存入了100,訪問login.aspx就會跳轉到獲取cookies頁面,提示登錄id=100,效果圖如下:
?
轉載于:https://www.cnblogs.com/chenlihong-886/p/6246073.html
總結
以上是生活随笔為你收集整理的程序中保存状态的方式之Cookies的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 泛型DAO与泛型Service
- 下一篇: NYOJ 998