ViewState Vs Session ... 通过页面生命周期维护对象 [英] ViewState Vs Session ... maintaining object through page lifecycle

查看:33
本文介绍了ViewState Vs Session ... 通过页面生命周期维护对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

谁能解释一下 ViewState 和 Session 的区别?

Can someone please explain the difference between ViewState and Session?

更具体地说,我想知道在我的页面的整个生命周期中保持对象可用(通过回发不断设置成员)的最佳方法.

More specifically, I'd like to know the best way to keep an object available (continuously setting members through postbacks) throughout the lifecycle of my page.

我目前使用 Sessions 来做到这一点,但我不确定这是否是最好的方法.

I currently use Sessions to do this, but I'm not sure if it's the best way.

例如:

SearchObject searchObject;
protected void Page_Load(object sender, EventArgs e)
{
     if(!IsPostBack)
     {
         searchObject = new SearchObject();
         Session["searchObject"] = searchObject;
     }
     else
     {
         searchObject = (SearchObject)Session["searchObject"];
     }
}

这允许我在页面上的任何其他地方使用我的 searchObject,但这有点麻烦,因为如果我更改任何属性等,我必须重置会话变量.

that allows me to use my searchObject anywhere else on my page but it's kind of cumbersome as I have to reset my session var if I change any properties etc.

我认为必须有更好的方法来做到这一点,以便 .NET 不会在每次页面加载时重新实例化对象,而是将其置于 Page 类的全局范围内?

I'm thinking there must be a better way to do this so that .NET doesn't re-instantiate the object each time the page loads, but also puts it in the global scope of the Page class?

推荐答案

如果搜索对象不是很大,那么继续使用 ViewState.如果您只希望对象在当前页面的生命周期内存活,则 ViewState 是完美的.

If the search object isn't huge in size, then go with using a ViewState. A ViewState is perfect if you only want the object to live for the current page's lifecycle.

会话对象也很好用,但显然一旦搜索对象在那里,它就会在页面的生命周期中存在更长的时间.

A session object is also fine to use, but obviously once the search object is in there, it will be around for longer the page's lifecycle.

另外,我对 ViewState/Session 对象做的一件事是用一个属性包装它们的访问:

Also, one thing I do with ViewState/Session objects is wrap their access with a property:

public object GetObject
{
    get
    {
        return ViewState["MyObject"];
    }
    set
    {
        ViewState["MyObject"] = value;
    }
}

我倾向于觉得这样做更干净.只需更改以上代码即可满足您的需求.

I tend to find it cleaner to do it this way. Just change the above code to fit your needs.

来源 2

这篇关于ViewState Vs Session ... 通过页面生命周期维护对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆