在 ASP.Net 中,VIEwState 因為在客戶端的 Html 裡占據大量的空間,並隨著頁面的 PostBack 反復傳遞於網絡中,一直為人垢病。但是實際上 VIEwState 可以存儲到數據庫、緩存等任意地方,從而避免頻繁將冗長的 base64 字符串發送到客戶端。這樣做不但可以顯著提高性能(大幅度減少了網絡傳輸的字節數),而且如果其中的內容也不會被輕易解密和破解。因此這個方法是很有用處的。
以下寫了一個簡單的例子,用緩存來作為 VIEwState 存儲目的地。至於緩存的 Key,文中給出的只是一個簡單的寫法,具體可以根據情況給出嚴密的方案。
代碼大致演示如下:
<%@ Page language="c#" Codebehind="SaveVIEwStateToOther.ASPx.cs" AutoEventWireup="false" Inherits="LinkedList.SaveVIEwStateToOther" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD Html 4.0 Transitional//EN" >
<Html>
<head>
<title>SaveVIEwStateToOther</title>
<meta name="GENERATOR" Content="Microsoft Visual Studio .Net 7.1">
<meta name="CODE_LANGUAGE" Content="C#">
<meta name=vs_defaultClIEntScript content="JavaScript">
<meta name=vs_targetSchema content="http://schemas.microsoft.com/intellisense/IE5">
</head>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server"><ASP:DataGrid id=DataGrid1 runat="server" BorderColor="#3366CC" Border BorderWidth="1px" BackColor="White" CellPadding="4" PageSize="6" AllowPaging="True">
<selecteditemstyle font-bold="True" forecolor="#CCFF99" backcolor="#009999">
</SelectedItemStyle>
<itemstyle forecolor="#003399" backcolor="White">
</ItemStyle>
<headerstyle font-bold="True" forecolor="#CCCCFF" backcolor="#003399">
</HeaderStyle>
<footerstyle forecolor="#003399" backcolor="#99CCCC">
</FooterStyle>
<pagerstyle horizontalalign="Left" forecolor="#003399" backcolor="#99CCCC" pagebuttoncount="20" mode="NumericPages">
</PagerStyle>
</ASP:DataGrid>
</form>
; </body>
</Html>
using System;
using System.Data;
using System.IO;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace LinkedList
{
/// <summary>
/// SaveVIEwStateToOther 的摘要說明。
/// </summary>
public class SaveVIEwStateToOther : Page
{
protected DataGrid DataGrid1;
private void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Bind();
}
private void Bind()
{
DataTable table = new DataTable();
table.Columns.Add("id", typeof (int));
table.Columns.Add("name", typeof (string));
for (int i = 0; i < 1000; i++)
{
DataRow row = table.NewRow();
row["id"] = i;
row["name"] = "student_" + i.ToString();
table.Rows.Add(row);
}
DataGrid1.DataSource = table;
DataGrid1.DataBind();
}
#region Web 窗體設計器生成的代碼
protected override void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.DataGrid1.PageIndexChanged += new System.Web.UI.WebControls.DataGridPageChangedEventHandler(this.DataGrid1_PageIndExchanged);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
protected override void SavePageStateToPersistenceMedium(object vIEwState)
{
LosFormatter format = new LosFormatter();
StringWriter writer = new StringWriter();
format.Serialize(writer, vIEwState);
string vsRaw = writer.ToString();
byte[] buffer = Convert.FromBase64String(vsRaw);
string vsText = Encoding.ASCII.GetString(buffer);
object v = Cache[PageKey];
if (v == null)
Cache.Insert(PageKey, vsText);
else
Cache[PageKey] = vsText;
}
public string PageKey
{
get { return Session.Se
ssionID + "_page_SaveVIEwStateToOther_ASPx"; }
}
protected override object LoadPageStateFromPersistenceMedium()
{
object s = Cache[PageKey];
if (s != null)
{
string state = s.ToString();
byte[] buffer = Encoding.ASCII.GetBytes(state);
string vsRaw = Convert.ToBase64String(buffer);
LosFormatter formatter = new LosFormatter();
return formatter.Deserialize(vsRaw);
}
return null;
}
private void DataGrid1_PageIndExchanged(object source, DataGridPageChangedEventArgs e)
{
DataGrid1.CurrentPageIndex = e.NewPageIndex;
Bind();
}
}
}
對於實際的應用,如果要決定在整個程序中應用此方案,則使用一個通用的頁面基類,在其中實現此機制比較合適。
出處:木野狐 BLOG