Question

Let's say that in an ASP.NET .aspx page I have the Page Load method and another method for a button click event.

In the Page Load method I'm checking if the user is logged in by checking the Session. Whether he is or not, I'm storing the result in a Global Variable.

Boolean isGuest = false;

protected void Page_Load(object sender, EventArgs e) {

        if(Session["id"]==null)
              isGuest = true;
        else
              isGuest = false;
}

Let's say 20 minutes have passed, and I don't know if the Session has terminated or not, and then I click a Button, the event goes like this:

protected void Button_Click(object sender, EventArgs e) {
            if(isGuest==false)
                 //do something
            else
                 // do another thing
}

My Question is : When I'm clicking the button, does ASP.NET go through the Page_Load method again (check isGuest again) or it simply executes what's inside the Button_Click method, means, it uses a Boolean isGuest that could be false, but in reality the session is terminated, means it should be true.

Was it helpful?

Solution

Page_Load is triggered always before the control events.

Have a look: ASP.NET Page Life Cycle Overview

Side-note: If you want to do things only on the first load and not on every postback you have to check the IsPostBack property.

OTHER TIPS

You can:

  1. Define your own class with the UserID, and other profile properties;
  2. Add that class to session in the global.asax session started event Session["NameReferingToYourClass"] = new YourClass();
  3. Set a member variable to your session object early in the page life cycle mYourClass = Session["NameReferingToYourClass"] casted if you need to;
  4. Then you can make any changes to your class anywhere in the code your member variable is available;
  5. Save back your class with all the changes into session on the Page.Unload(..){ Session["NameReferingToYourClass"] = mYourClass.

This way you are using your class properties in your code, including UserId, pretty much like a windows application, there will be no mentioning of session anywhere else in your code.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top