0

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?

Arioch 'The
  • 15,799
  • 35
  • 62
iMan Biglari
  • 4,674
  • 1
  • 38
  • 83

2 Answers2

1

Page_PreInit does run before any click event handlers.

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

tunerscafe
  • 91
  • 8
  • Yes. Takes too much time for me – iMan Biglari Jan 09 '13 at 12:17
  • 1
    Rather than using a button with an onClick event you could always use a standard HTML control with a QueryString parameter something like print=1 or print=0. The querystring is available in the request object in the Page_PreInit method. Then use this to set the Session variable at the begining of the Page_PreInit method. – tunerscafe Jan 09 '13 at 12:36
0

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';
iMan Biglari
  • 4,674
  • 1
  • 38
  • 83