自定义ViewState的保存方式

大家都知道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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值