How to properly change a page's master page?

179 Views Asked by At

I have two master pages in my ASP.NET application. One for regular use, and another for printing. I use a session parameter to see if the application is currently in print mode or not:

method Global.Application_PreRequestHandlerExecute(src: System.Object; e: EventArgs);
begin
  var p: System.Web.UI.Page := System.Web.UI.Page(self.Context.Handler);
  if p <> nil then begin
    p.PreInit += new EventHandler(page_PreInit)
  end
end;

method Global.page_PreInit(sender: System.Object; e: EventArgs);
begin
  var p: System.Web.UI.Page := System.Web.UI.Page(self.Context.Handler);
  if p <> nil then
    if p.Master <> nil then
    begin
      if Session['P'].ToString = '1' then
        p.MasterPageFile := '~/Print.Master'
      else
        p.MasterPageFile := '~/Site.Master'; 
    end;
end;

I have one button on my normal page which sets Session['P'] to '1', and another on my print master page which sets Session['P'] to '0'. Now, my problem is that after the I have changed the session parameter in my code, the page is rendered using the obsolete master page, and not the current one. The user has to hit F5 to see the correct page. It almost seems like my page_PreInit() event is fired before buttonClick(). So, what can I do?

2

There are 2 best solutions below

0
iMan Biglari On BEST ANSWER

I finally used Request.Params['__EVENTTARGET'] in my Page_PreInit event to determine if the clicked control is the button tasked with switching between normal and print modes. My code looks like this:

S := Request.Params['__EVENTTARGET'];
if S.Length > 0 then
  S := S.Substring(S.IndexOf('$') + 1);
if S = 'lbPrint' then
  Session['P'] := '1'
else if S = 'lbNormal' then
  Session['P'] := '0';
2
tunerscafe On

Page_PreInit does run before any click event handlers.

Have you considered using panels or stylesheets to render your page in print mode?