1

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:

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
    }
}

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.

LocustHorde
  • 6,361
  • 16
  • 65
  • 94

1 Answers1

3

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.

StriplingWarrior
  • 151,543
  • 27
  • 246
  • 315
  • Hi, this is great, but everytime I access my ``_model`` it comes back with ``object reference not set to an instance...`` exception? – LocustHorde Jul 28 '11 at 16:54
  • 1
    @LocustHorde: _model starts out with a null value and will continue to be null until you set it to something else. Where do you set the value of `_model`? Where do you try to access it? Can you set breakpoints to determine when those events happen in relation to `LoadViewState` and `SaveViewState` being called? – StriplingWarrior Jul 28 '11 at 17:10
  • okay, my mistake, I wasn't setting it to anything on page load. Thanks a bunch, you have helped me more times than I can count! – LocustHorde Jul 28 '11 at 17:13
  • I was getting/setting this on properties and page load functions and it was a nightmare. Thank you for teaching me something new! – Tomas Beblar Jan 03 '22 at 22:32