/// <summary> /// 从保存的位置加载数据。 /// </summary> private void LoadViewState() { //加载 string str = ""; #region 提取数据 switch (SaveLocation) { case SaveViewStateLocation.Cookie: if (HttpContext.Current.Request.Cookies[ClientID] == null) { return; } str = HttpContext.Current.Request.Cookies[ClientID].Value; break; case SaveViewStateLocation.Hidden: if (Page == null) { return; } if (HttpContext.Current.Request[ClientID] == null) { return; } str = HttpContext.Current.Request[ClientID]; break; case SaveViewStateLocation.Session: str = HttpContext.Current.Session[ClientID].ToString(); break; case SaveViewStateLocation.Cache: str = HttpContext.Current.Cache[ClientID].ToString(); break; case SaveViewStateLocation.Application: str = HttpContext.Current.Application[ClientID].ToString(); break; } #endregion if (str.Length == 0) //没有取到值 { return; } if (Key.Length > 0) { //解密 str = DesBase64.Decrypt(str, Key); } //拆分 string[] arr = str.Split('`'); //赋值 for (int i = 0; i < arr.Length; i += 2) { if (!vs.ContainsKey(arr[i])) { vs.Add(arr[i], arr[i + 1]); } } }
/// <summary> /// 把数据保存到指定的位置里面。 /// </summary> private void SaveViewState() //virtual object { //拼接字符串 var str = new StringBuilder(1000); foreach (KeyValuePair <string, string> entry in vs) { str.Append(entry.Key); str.Append("`"); str.Append(entry.Value); str.Append("`"); } if (str.Length == 0) //没有赋值 { return; } str.Remove(str.Length - 1, 1); string myData = str.ToString(); if (Key.Length > 0) { //加密 myData = DesBase64.Encrypt(myData, Key); } str.Length = 0; #region 保存 switch (SaveLocation) { case SaveViewStateLocation.Cookie: //HttpContext.Current.Response.Cookies[ClientID].Value = myData; var httpCookie = HttpContext.Current.Response.Cookies[ClientID]; if (httpCookie != null) { httpCookie.Value = myData; } break; case SaveViewStateLocation.Hidden: #region if (Page != null) { Page.ClientScript.RegisterHiddenField(ClientID, myData); } #endregion break; case SaveViewStateLocation.Session: HttpContext.Current.Session[ClientID] = myData; break; case SaveViewStateLocation.Cache: HttpContext.Current.Cache[ClientID] = myData; break; case SaveViewStateLocation.Application: HttpContext.Current.Application[ClientID] = myData; break; } #endregion }