Calling the original Page_Load function from inline code
Asked Answered
P

4

9

I like to Monkey patch a ASPX website so that I can add stuff to the Page_Load method within a compiled assembly.

My first thought was to add a script tag containing a second Page_Load method to the ASPX file like so:

<script language="CS" runat="server">
void Page_Load(object sender, System.EventArgs e) 
{
     // do some stuff in addition to the original Page_Load method
}
</script>

But it looks like only the Page_Load method from the inline code will be executed and not the one from the original code-behind file (within the compiled assembly).

Is it possible to call the original method from within my inline code? Or is there any other way to add stuff that should run directly after the Page_Load method was called from within inline code without modifying the existing assembly?

Procreate answered 7/7, 2011 at 14:40 Comment(0)
D
10

The asp.net model is that the page declared in the .aspx file is actally a descendant class from the class that inherits from System.Web.UI.Page declared in the .aspx.cs file.

So your Page_Load method is called because it basically hides the original Page_Load method. Following that logic, you could do:

<script language="CS" runat="server"> 
void Page_Load(object sender, System.EventArgs e)  
{      
   base.Page_Load(sender, e);
   // do some stuff in addition to the original Page_Load method 
} 
</script> 

There are no accessibility issues because asp.net by default declares Page_Load and similar methods as protected so descendant classes can call them.

Daydream answered 7/7, 2011 at 14:46 Comment(1)
Should be base.Page_Load(sender, e);Immorality
S
3

Yes it is:

void Page_Load(object sender, System.EventArgs e) 
{
     // Do some things before calling the original Page_Load
     base.Page_Load(sender, e);
     // Do some things after calling the original Page_Load
}

The reason this works is that the ASP.Net framework operates on the model where the .aspx file gets compiled up into a class that inherits from the class defined in your code behind file (actually the class defined by the Inherits attribute on the page tag)

<%@ Inherits="WebApplication1._Default" ... 
Stalinabad answered 7/7, 2011 at 14:45 Comment(0)
L
0

You can also try to use PreLoad method. Those get called before Page_Load and might be a cleaner way to handle things.

Legging answered 7/7, 2011 at 14:46 Comment(0)
I
0

This works for me.

<script language="CS" runat="server"> 
    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        Response.Write("additional stuff");
    } 
</script>
Incorporated answered 7/7, 2011 at 14:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.