开发者

Load viewstate on pageload, save on Page Unload (from baseclass) - c# Asp.net

Pardon me for asking a mundane newbie question but I seem to be stuck in a class life-cycle limbo.

So I have my page

public partial class DefaultPage : BasePage
{ 
    ...
}

And the BasePage like this:

publ开发者_如何学Cic 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
    }
}

Now I just want to get the Modal on page load, which I do from constructor. How can I save it on page unload? I can't use destructor as It's not reliable.

What is the best solution to this scenario?

Thanks.


LoadViewState and SaveViewState are appropriate methods for this.

    protected override void LoadViewState(object savedState)
    {
        base.LoadViewState(savedState);
        _model= (Model) ViewState["_model"];
    }

    protected override object SaveViewState()
    {
        ViewState["_model"] = _model;
        return base.SaveViewState();
    }

Using these methods guarantees that the ViewState has been loaded from the PostBack before you try loading a value from it, and that you have placed the necessary values into the ViewState before the ViewState is rendered to the output.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜