Deep asp.net Web Page

Source: Internet
Author: User
Tags bind constructor contains execution final generator reference client
Asp.net|web first, Introduction to Server Scripting Basics

First, let's review the basics of how Web Server Pages are executed:

1, the client through the browser's address bar typing address to send the request to the server side

2, the server received the request, sent to the corresponding server-side page (that is, script) to execute, the script produces the client's response, sent back to the client

3. The client browser receives the response from the server, parses the HTML and renders the graphical page in front of the user

For server and client interaction, there are usually several main ways to do this:

1, form: This is the most important way, standardized control to get user input, form submission to send data to server-side processing

2, QueryString: By the URL after the parameter to reach the parameters to the server, this way in fact, and get the form is the same

3, Cookies: This is a more special way, usually used for the identification of users

Second, ASP. NET Introduction

The traditional server scripting language, such as ASP, JSP, and so on, the way to write server script, are embedded in the Html interpretation or compile the execution of code, the server platform to execute the code to generate Html; for this similar script, the life cycle of the page is actually very simple, from the beginning to the end, By executing all the code, of course, a servlet written in Java can write more complex code, but structurally, it's no different from JSP.

Asp. NET, broke the tradition; ASP.net adopted the codebehind technology and server-side control, added the concept of server-side events, changed the script language writing mode, more close to window programming, so that the Web programming more simple, intuitive; but we want to see that ASP . Net itself does not change the basic pattern of WEB programming, but encapsulates some details, provides some Easy-to-use functionality, makes code easier to write and maintain, and, to some extent, complicates the way the server side executes, which is what we're going to talk about today: asp.net Web The life cycle of the page.

Third, ASP. NET Request processing mode

We say, ASP. NET Web page does not break out of the Web programming model, so it is still working in a pattern of requesting-> receiving requests-> processing requests-> sending responses, and every interaction with the client raises a new request, so a web The page life cycle is based on a single request.

When IIS receives a request from the client, the request is handed over to the aspnet_wp process, which looks at whether the requested application domain exists, creates one if it does not exist, and then creates an HTTP runtime (HttpRuntime) to process the request, the runtime " Provides a set of ASP.net runtime services for the current application (excerpted from MSDN).

HttpRuntime maintains a series of application instances while processing the request, That is, an instance of the application's global Class (global.asax), which, when not requested, is stored in an application pool (in fact, the application pool is maintained by another class, httpruntime is simply called), and each time a request is received, HttpRuntime acquires a Idle instances to process requests that do not process other requests until the end of the request, and then return to the pool after processing, "an instance is used to process multiple requests during its lifetime, but it can process only one request at a time." "(excerpted from MSDN)

When an application instance processes a request, it creates an instance of the request page class and executes its ProcessRequest method to handle the request, which is the beginning of the Web page life cycle.

Four, aspx page and codebehind

Before delving into the life cycle of a page, let's look at some of the relationships between ASPX and Codebehind.

<%@ Page language= "C #" codebehind= "WebForm.aspx.cs" inherits= "Mynamespace.webform"%>

Believe that the use of codebehind technology friends, the top of the ASPX sentence should be very familiar with, we come to an analysis of it:

Page language= "C #" This is not much to say

codebehind= "WebForm.aspx.cs" means a code file that is bound

Inherits= "Mynamespace.webform" is very important, it represents the class name that the page inherits, that is, the class in the Codebehind code file, this class must derive from the System.Web.WebControls.Page

From the above we can analyze, in fact, the class in Codebehind is a page (ASPX) base class, here, may be some friends to ask, in writing ASPX, completely in the form of ASP, in HTML code or embedded in the server control, did not see the so-called "class" Shadow, huh?

This question is not really complicated, and you can use ASP.net programming friends to your system disk: \windows\microsoft.net\framework\ < version >\temporary asp.net files directory, Here's a temporary file of all the ASP.net applications that exist on this computer. The name of the subdirectory is the name of the application, and then it goes down two tiers (to ensure uniqueness, ASP.net automatically generates a two-tier subdirectory, and the subdirectory name is random), and then we find that there are many similar: " Yfy1gjhc.dll "," xeunj5u3.dll "such as the link library and" Komee-bp.0.cs "," 9falckav.0.cs "such a source file, in fact, this is ASPX by ASP. NET dynamically compiled results, open these source files we can find:

public class WebForm_aspx:MyNamespace.WebForm, System.Web.SessionState.IRequiresSessionState

This confirms what we said earlier, ASPX is a subclass of the code-bound class whose name is the ASPX filename plus the "_aspx" suffix, and by studying the code we can find that virtually all of the server controls defined in ASPX are generated in these codes, and then dynamically generate the code, Write the code that was originally embedded in ASPX in the appropriate location.

When a page is accessed for the first time, the HTTP runtime uses a code generator to parse the ASPX file and generate the source code and compile it, then call the compiled DLL directly later, which is why ASPX was very slow on its first visit.

To explain the problem, let's look at another question. When we use code binding, we drag a control on the design page and switch to Code view, we can use the control directly in the Page_Load, since the control is generated in the subclass, why is it possible to use it directly in the parent class?

In fact, we can see that every time you drag a control onto a page with Vs.net, the code-bound file always adds a declaration like this:

protected System.Web.WebControls.Button Button1;

We can see that this field is declared as protected and the name is consistent with the ID of the control in ASPX, and the problem is solved by thinking it over. We mentioned earlier that the source code for ASPX was generated and compiled dynamically by the generator, which generates code that dynamically generates each server control, and when generated, it checks that the parent class has declared the control, and if it does, it adds a code similar to the following:

This. DATAGRID1 = __ctrl;

This __ctrl is the variable that generates the control, and it assigns the reference of the control to the corresponding variable in the parent class, which is why the declaration in the parent class must be protected (and can actually be public), because the subclass is guaranteed to be callable.

Then when executing the Page_Load, because the declaration of the parent class is already assigned a value in the initialization code in the quilt class, so we can use this field to access the corresponding control, we will not commit to use the control in the constructor in the code binding file, causing the exception of the null reference error, Because the constructor is executed first, the initialization of the subclass has not yet begun, so the field in the parent class is NULL, and when the subclass is initialized we put it behind the discussion.

Five, page life cycle

Now back to the third title, we talked about the instance of HttpApplication receiving the request and creating an instance of the page class, which is actually an instance of the dynamically compiled ASPX class, which we learned in the previous header that ASPX is actually a subclass of the class in code binding. So it inherits all the protected methods.

Now let's take a look at the code for the Codebehind class that vs.net automatically generates to begin our discussion of the page life cycle:

#region Web Form Designer generated code

Override protected void OnInit (EventArgs e)

{

//

CodeGen: This call is required for the ASP.net Web forms Designer.

//

InitializeComponent ();

Base. OnInit (e);

}

<summary>

Designer supports required methods-do not use the Code editor to modify

The contents of this method.

</summary>

private void InitializeComponent ()

{

This. Datagrid1.itemdatabound + = new System.Web.UI.WebControls.DataGridItemEventHandler (this. Datagrid1_itemdatabound);

This. Load + = new System.EventHandler (this. Page_Load);

}

#endregion

This is the use of Vs.net generated page code, we see that there are two methods, one is OnInit, one is InitializeComponent, the latter is called by the former, actually this is the beginning of page initialization, in InitializeComponent we see the control 's event declaration and page's load declaration.

The following is a description of the excerpt from MSDN and a sequential table of page lifecycle methods and event triggers:

"Each time a ASP.net page is requested, the server loads a asp.net page and unloads the page when the request completes." The page and the server controls it contains are responsible for executing the request and rendering the HTML to the client. Although the communication between the client and the server is stateless and intermittent, the customer must feel that this is a sequential process. ”

"This illusion of continuity is implemented by ASP.net page frames, pages, and their controls." After a postback, the behavior of the control must appear to start where the last Web request ended. Although the ASP.net page framework makes execution state management relatively easy, control developers must know the order in which controls are executed in order to achieve continuity. Control developers need to understand what information the control can use at various stages of the control lifecycle, what data to keep, and in what state the control renders. For example, a control cannot call its parent until the control tree on the page is populated. ”

The following table provides a high-level overview of the stages in the control lifecycle. For more information, click on the link in the table. ”

Stage
Actions that the control needs to perform
The method or event to override

Class
Initializes the settings that are required within the life cycle of the incoming WEB request. See Handling inherited events.
Init Event (OnInit method)

Load View state
At the end of this phase, the ViewState property of the control is automatically populated, as described in maintaining the state in the control. Control can override the default implementation of the LoadViewState method to customize the state restore.
LoadViewState method

Processing postback data
Process incoming form data and update the properties accordingly. See Processing postback data.

Note Only controls that process postback data participate in this phase.
LoadPostData method

(if IPostBackDataHandler is implemented)

Load
Perform actions that are common to all requests, such as setting up a database query. At this point, the server control in the tree has been created and initialized, the state has been restored, and the form control reflects the client's data. See Handling inherited events.
Load Event

(OnLoad method)

Send a postback change notification
Raises a change event to respond to a state change between the current and the previous postback. See Processing postback data.

Note Only controls that raise postback change events are involved in this phase.
RaisePostDataChangedEvent method

(if IPostBackDataHandler is implemented)

Handling Postback Events
Handles the client event that caused the postback and raises the appropriate event on the server. See catching postback events.

Note Only controls that handle postback events participate in this phase.
RaisePostBackEvent method

(if IPostBackEventHandler is implemented)

Pre-rendering
Performs any updates before rendering the output. You can save changes to the state of the control at the present stage, and changes that are made to the rendering phase are lost. See Handling inherited events.
PreRender Events

(OnPreRender method)

Save state
After this phase, the control's ViewState property is automatically persisted to the string object. This string object is sent to the client and sent back as a hidden variable. To improve efficiency, controls can override the SaveViewState method to modify the ViewState property. See maintaining state in a control.
SaveViewState method

Present
Generates output that is rendered to the client. See rendering ASP.net server controls.
Render method

Disposal
Performs all final cleanup operations before destroying the control. References to expensive resources, such as database links, must be released at this stage. See the methods in ASP.net server controls.
Dispose method

Unloading
Performs all final cleanup operations before destroying the control. Control authors typically perform cleanup in Dispose without handling this event.
UnLoad event (on UnLoad method)

From this table we can clearly see a page from load to unload between the method and the trigger time, and then we in-depth analysis of it.

Looking at the table above, the attentive friend may ask, since OnInit is the beginning of the page life cycle, and we talked about the control being created in the subclass in the last lecture, so here we can actually use the famous field in the parent class in the InitializeComponent method. So that means the initialization of subclasses is more than that?

In the third title we talked about the ProcessRequest of the page class is the beginning of the real sense of the page declaration cycle, this method is called by the HttpApplication (in which the way is more complex, there is a chance to write alone to explain), A page's processing of requests begins with this method and is compiled by decompile. NET class library to view the source code, we found that in the base class of System.Web.WebControls.Page: System.Web.WebControls.TemplateControl (which is the base class of the page and user control) defines a " FrameworkInitialize the virtual method, and then the method was first invoked in the page ProcessRequest, where we found traces of the method in the source code of the ASPX generated by the generator, and all the controls were initialized in this method, The page's control tree is generated at this time.

The next thing is simple, and we're going to step through each of the pages ' lifecycle:

1. Initialization

Initializes the Init event and OnInit method corresponding to the page.

If overridden, the MSDN recommendation is to overload the Oninti method, rather than adding a proxy for an INIT event, which can control the order in which the parent class OnInit methods are invoked, The latter can only be executed after the oninit of the parent class (which is actually called in the OnInit).

2. Load View state

This is a more important method, we know, for each request, is actually a different page class instances to deal with, in order to ensure the status of two requests, ASP. NET uses the ViewState, regarding ViewState's description, please refer to my another article:

Http://expert.csdn.net/Expert/top ... 98.xml?temp=.2561609

The LoadViewState method is to get the last state from the viewstate, and according to the structure of the page's control tree, iterate through the tree with recursion, and restore the corresponding state to each control.

3, processing the postback data

This method is used to check whether the state of the control data that the client sends back has changed. The prototype of the method:

Public virtual bool LoadPostData (string postdatakey, NameValueCollection postcollection)

Postdatakey is the keyword that identifies the control (that is, the key in Postcollection), Postcollection is the collection that contains postback data, we can override this method, and then check that the postback data has changed, and if so, return a true , "LoadPostData returns True if the control state changes because of a postback, otherwise it returns false. The page framework tracks all controls that return true and invokes raisepostdatachangedevent on those controls. "(excerpted from MSDN)

This method is defined in System.Web.WebControls.Control and is the way that all custom controls that need to handle events need to be handled, and for the page we're talking about today, you don't have to worry about it.

4, loading

Load the corresponding Load event and onload method, for this event, I believe most friends will be more familiar with the vs.net generated page Page_Load method is the response to the Load event method, for each request, the Load event will trigger, Page_ The Load method is also performed, and it is believed to be the first step in most people's understanding of asp.net.

The Page_Load method responds to the Load event, which is defined in the System.Web.WebControl.Control class (this class is the ancestor of page and all server controls) and is triggered in the OnLoad method.

Many people may have encountered such a thing, wrote a Pagebase class, and then in Page_Load to verify the user information, and found that regardless of whether the validation is successful, the Page_Load of the subclass page will always execute first, this time is likely to leave some security risks, The user may execute the Page_Load method in subclasses without being authenticated.

The reason for this problem is simple because the Page_Load method is added to the Load event in OnInit, and the OnInit method of the subclass is to add the Load event first and then call base. OnInit, this causes the Page_Load of the subclass to be added first, then executes first.

There are two ways to solve this problem:

1 overload the OnLoad method in Pagebase, then validate the user in onload and call base. OnLoad, because the load event is triggered in onload so that we can ensure that the user is validated before the load event is triggered.

2 Call Base.oninit in the OnInit method of the subclass to ensure that the parent class executes the Page_Load first

5, send a postback change notice

This method corresponds to the processing of the 3rd step postback data, if processing postback data returns TRUE, the page frame calls this method to trigger the data change event, so the postback data change event for the custom control needs to be triggered in this method.

The same method is not very useful for page, of course you can also define the events of the data change on the basis of page.

6, handling the postback event

This method is where most server control events are raised, and when the request contains information that the control event triggers (the server control event is another topic that I will discuss in the near future), the page control invokes the RaisePostBackEvent method of the corresponding control to raise the server-side event.

Here's another common problem:

Often have netizens ask, why modify the data after the submission has not changed

Most of the cases are that they do not understand the triggering process of the server events, we can see that the trigger server event is after page Load, that is, the page will execute the Page_Load before the button (here to the button as an example) of the Click event, many friends are in the Page_ Load to bind the data, and then handle the changes in the button events, there is a problem, Page_Load always in front of the button event, meaning that the data has not yet been changed, the Page_Load data binding code is executed first, the original data is assigned to the control, Then the implementation of the button event, actually get the original data, then the update of course has no effect.

Changing the problem is also very simple, it is more reasonable to write data-bound code as a method, we assume that the Binddata:

private void Binddata ()

{

Binding Data

}

Then modify the pageload:

private void Page_Load (object Sender,eventargs E

{

if (! IsPostBack

{

Binddata (); Bind data when the page is first accessed

}

}

Finally, in the button event:

Private Button1_Click (Object Sender,eventargs E

{

Update data

Binddata ()//rebind data

}

7. Pre-Presentation

The processing of the final request is turned into a response that is sent back to the server. This stage of staging is a change in the state that was made before the final rendering, because before rendering a control, we had to produce Html based on its properties, such as the Style property, which is the most typical example, before rendering, We can change the style of a control, and when we perform a pre rendering, we can save the style as the style information for displaying the HTML in the render phase.

8, Save the state

This phase is for the loading state, we have mentioned many times, requests are different instances of processing, so we need to save the state of the page and control, this stage is to write the state to the ViewState phase. Http://csharp.xdowns.com

9. Present

Here, in fact, the page on the processing of the request basically ended, in the Render method, the entire page will be recursive control tree, call the Render method in turn, the corresponding HTML code written to the final response stream.

10, disposal

is actually the Dispose method, which frees up resources, such as database connections, in this phase.

11. Uninstall

Finally, the page executes the OnUnload method to trigger the Unload event, dealing with the final processing before the Page object is destroyed, in fact ASP.net provides this event only in the design consideration, usually the release of the resources will be done in the Dispose method, so this method also becomes chicken.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.