What methods are executed in what order on this page of ASP.NET web forms?

The other day, I reorganized some old website and came across this scenario. I have an ASP.NET 3.5 C # WebForms page. In the code behind, I have an event handler, for example:

protected override void OnPreRender(EventArgs e) { } 

On the other hand, in the markup, I also have:

 <script language="C#" runat="server"> void Page_PreRender() { } </script> 

Question: what does the life cycle look like? What is done first? Is one of them even done?

+6
source share
1 answer

Two points:

  • The OnPreRender method OnPreRender not an event handler. This is an override of the Page.OnPreRender method (which is the method that will PreRender event).
  • The Page_PreRender method Page_PreRender automatically connected to the PreRender event. Thus, it is an event handler (for the PreRender event).

Call order

The following code example shows the execution order:

 // code-behind protected override void OnPreRender(EventArgs e) { // 1. code put here will be executed first // now we call the base class' version, which will then raise the // PreRender event base.OnPreRender(e); // 3. code put here will be executed last } // markup <script language="C#" runat="server"> void Page_PreRender() { // 2. code put here will be executed second } </script> 

Note that inside OnPreRender() , the base class is called: base.OnPreRender() . As indicated above, if this is absent, the PreRender event PreRender not be raised, so event handlers will not be called.

Code example

Your code sample base.OnPreRender not have a call to base.OnPreRender . This means that the PreRender event PreRender not occur, and therefore the method (event handler Page_PreRender() will not be called.

A few more points to consider

  • If you have a Page_PreRender() event handler in your markup and in your code, only the one in the code will be called.

  • If you disable automatic posting of events in the page directive (for example, < % @ Page AutoEventWireup="false" ... % > ), then the Page_PreRender() event handler will not be connected / connected to the PreRender event and therefore will not be called.

  • You can also manually attach event handlers to events, for example:


  protected void Page_Load(object sender, EventArgs e) { PreRender += PreRenderEventHandler; } void PreRenderEventHandler(object sender, EventArgs e) { } 
+2
source

Source: https://habr.com/ru/post/986087/


All Articles