自定义ViewState的保存方式

来源:互联网 发布:鹦鹉螺雾化芯diy数据 编辑:程序博客网 时间:2024/06/10 04:08
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
大家都知道Asp.Net中使用ViewState来在客户端与服务端之间保存页面中的信息及用户自定义的信息.
在2.0之前的版本中,ViewState是保存在页面中的隐藏控件中的:__ViewState
我们无法改变ViewState保存方式及保存位置.
现在在2.0中,Asp.Net开放了这个功能,允许我自定义ViewState的保存位置.
在2.0的Page类中新增了一个属性:PageStatePersister.
我们可以重写这个属性来实现自定义ViewState的保存.这个属性要返回一个继承自PageStatePersister类的子类的一个实例.
2.0中默认提供了两种保存方法:一个是保存在页面中(HiddenFieldPageStatePersister ),另外一个是保存在Session中(SessionPageStatePersister ).
下面的代码重写了PageStatePersister属性,将ViewState保存到Session中:

protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}
除了这两种默认的保存方式外,我们可以继承PageStatePersister类,来实现自己的保存方式.
以下的代码演示了如果将ViewState保存到文件中:
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;


/**//// <summary>
/// CWingViewState 的摘要说明
/// </summary>
public class CWingViewState : PageStatePersister
{
public CWingViewState(Page page):base(page)
{
}

public override void Load()
{
ReadFile();
}

public override void Save()
{
WriteFile();
}

private void WriteFile()
{
FileStream file = File.Create(@"C:/CustomerViewState.CW");
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(file, base.ViewState);
file.Flush();
file.Close();
}

private void ReadFile()
{
FileStream file = File.OpenRead(@"C:/CustomerViewState.CW");
BinaryFormatter bf = new BinaryFormatter();
base.ViewState = bf.Deserialize(file);
}
}

具体的页面中:
protected override PageStatePersister PageStatePersister
{
get
{
return new CWingViewState(this);
}
}


出处:.Net空间 BLOG

<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 728x15, 创建于 08-4-23MSDN */google_ad_slot = "3624277373";google_ad_width = 728;google_ad_height = 15;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
<script type="text/javascript"><!--google_ad_client = "pub-2947489232296736";/* 160x600, 创建于 08-4-23MSDN */google_ad_slot = "4367022601";google_ad_width = 160;google_ad_height = 600;//--></script><script type="text/javascript"src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
原创粉丝点击