views:

66

answers:

3

I need the following functionality in my method: if the method is called before OnLoad event of ASP.NET life cycle throw an exception else continue execution of the method.

I was thinking of something like this:

if (Page.LifeCycleState < LifeCycleState.OnLoad) {
    throw new InvalidPageStateException();
}

Is it possible to retrieve the state of ASP.NET page life cycle?

+4  A: 

One approach would be to use a Basepage that you always use in your site. This would contain a variable called PageLoadComplete, which you would set at the end of your PageLoad event. Then you could check the state of this variable from within your method.

public abstract class BasePage : System.Web.UI.Page
{
    public bool PageLoadComplete { get; private set; }
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);
        PageLoadComplete = true;
    }
}

If you want to access the variable from code external to your page such as a UserControl, you would have to make it public and cast your page as BasePage.

public partial class MyUserControl : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        BasePage basePage = this.Page as BasePage;
        if (basePage != null && !basePage.PageLoadComplete)
        {
            throw new InvalidPageStateException();
        }
    }
}
Daniel Dyson
Thanks @abatishchev
Daniel Dyson
A: 

You maybe able to find what you are looking for, by looking at the CurrentHandler and PreviousHandler properties of the current HttpContext.

leppie
I need the information about page state. I do not understand how to retrieve it from HttpContext.
Petr Kozelek
A: 

There is property in a realization of System.Web.UI.Control class(realization):

    internal ControlState ControlState { 
        get { return _controlState; }
        set { _controlState = value; } 
    } 

Where ControlState is enum that contains members such as: Initialized, ViewStateLoaded, Loaded etc. here declaration

But as you can see this property is internal. So only way to get control state is proposed by Daniel Dyson.

chapluck
Well, this is in Spring.NET. I asked for raw ASP.NET solution. Thanks anyway.
Petr Kozelek
My code examples are raw ASP.NET code. And only way to get control state is proposed by Daniel Dyson.
chapluck