请原谅我问了一个普通的新手问题,但我似乎被困在一个类的生命周期的边缘。
我有我的页面
public partial class DefaultPage : BasePage
{
...
}
和BasePage如下:
public class BasePage : System.Web.UI.Page
{
private Model _model;
public BasePage()
{
if (ViewState["_model"] != null)
_modal = ViewState["_model"] as Modal;
else
_modal = new Modal();
}
//I want something to save the Modal when the life cycle ends
[serializable]
public class Model
{
public Dictionary<int, string> Status = new Dictionary<int, string>();
... //other int, string, double fields
}
public class PageManager()
{ //code here; just some random stuff
}
}
现在我只想在页面加载时获得Modal,这是我从构造函数中完成的。如何在页面卸载时保存它?我不能使用析构函数,因为它不可靠。
这种情况的最佳解决方案是什么?
谢谢。
LoadViewState
和SaveViewState
是合适的方法。
protected override void LoadViewState(object savedState)
{
base.LoadViewState(savedState);
_model= (Model) ViewState["_model"];
}
protected override object SaveViewState()
{
ViewState["_model"] = _model;
return base.SaveViewState();
}
使用这些方法可以保证在你尝试从PostBack中加载一个值之前,ViewState已经被加载,并且在ViewState呈现到输出之前,你已经将必要的值放入ViewState中。