ViewState与Session ...通过页面生命周期维护对象

Kyl*_*yle 40 .net c# viewstate session global-scope

有人可以解释一下ViewState和Session之间的区别吗?

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

我目前使用Sessions来做这件事,但我不确定这是不是最好的方法.

例如:

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

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

我认为必须有一个更好的方法来实现这一点,以便.NET不会在每次加载页面时重新实例化对象,而且还将它放在Page类的全局范围内?

Jas*_*ans 60

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

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

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

public object GetObject
{
    get
    {
        return ViewState["MyObject"];
    }
    set
    {
        ViewState["MyObject"] = value;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

  • 很公平.我只是觉得这些话不合适.我不会再这样做了. (2认同)

Ben*_*son 28

First of all Viewstate is per page where as the session exists throughout the application during the current session, if you want your searchobject to persist across pages then session is the right way to go.

Second of all Viewstate is transferred as encrypted text between the browser and the server with each postback, so the more you store in the Viewstate the more data is going down to and coming back from the client each time, whereas the session is stored server side and the only thing that goes back and forth is a session identifier, either as a cookie or in the URL.

Whether the session or viewstate is the right place to store your search object depends on what you are doing with it and what data is in it, hopefully the above explanation will help you decide the right method to use.