ViewState的VS会话......通过页面生命周期维护对象 [英] ViewState Vs Session ... maintaining object through page lifecycle
问题描述
有人可以解释的ViewState和会话之间的区别?
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.
我目前使用的会话要做到这一点,但我不知道这是否是最好的方式。
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
{
if (ViewState["MyObject"] != null)
{
return ViewState["MyObject"];
}
return null;
}
set
{
ViewState["MyObject"] = value;
}
}
我往往会发现它的清洁剂做这种方式。只要改变上述code,以满足您的需求。
I tend to find it cleaner to do it this way. Just change the above code to fit your needs.
-
<一个href="http://www.articlesbase.com/programming-articles/how-to-choose-from-viewstate-session-application-cache-and-cookies-443393.html"相对=nofollow>源1
这篇关于ViewState的VS会话......通过页面生命周期维护对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!