Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No Page_PreLoad on masterpage?

I have a custom object in the Session which updates by postbacks on both the masterpage and the main page.

After the postback, I need to get the Session object, rebuild and modify parts of it or the whole object, and load it back into the Session.

I have written this code in the Page_Load of the main page. It works fine on only one page.

Now I have written an other page with the same masterpage, and I want the masterpage to be able to modify my session object just like before.

So I thought I just need to move the session handling code to the masterpage's Page_Load. But that did not work as I expected, as a control on the main page (namely a repeater) accesses the session object in the OnItemDataBound event's handler, BEFORE the masterpage's Page_Load fires, and this way it only gets the previous state of the session object. (It is only true for the repeater on the main page, the repeater on the masterpage gets the current state when it accesses the session)

No matter I thought I could use the Page_PreLoad event of the masterpage, I could access the postback data in the Page_PreLoad just as fine, and update the session object accordingly, but I found out there is NO Page_PreLoad on the masterpage, or I fail to use it.

Where should I update my object in the session?

To sum it up: I need a place in the masterpage's codebehind where postback data is ready to use, and neither of the main page's nor the masterpage's repeater's OnItemDataBound event have been fired yet.

like image 452
vinczemarton Avatar asked Dec 17 '22 17:12

vinczemarton


2 Answers

There is also another sollution: in the init event of the masterpage you can actually subscribe for the preload event of the page. consider this code in the masterpage:

    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);
        Page.PreLoad += OnPreLoad;
    }

    protected void OnPreLoad(object sender, EventArgs e)
    {
        //this function is in the masterpage but will be called on page preload event so do here your preload stuff ...
    }
like image 141
Grigor Margaritov Avatar answered Jan 01 '23 18:01

Grigor Margaritov


Hopefully I'm understanding this correctly - I think your best option is to create a base page, and make your pages inherit from this. Put your logic in the Page_Load or Page_PreLoad event handler in the base page. Master pages are loaded after the actual page starts to load.

So, you create a base page:

public class BasePage : Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      // sesion logic here
   }  
}

And make your page inherit from this (as well as using your master page):

public class Page1 : BasePage //instead of Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      base.Page_Load(sender, e);
   }  
}
like image 38
Graham Clark Avatar answered Jan 01 '23 17:01

Graham Clark