ASP. NET page Object Model

Source: Internet
Author: User
Http://www.microsoft.com/china/msdn/library/webservices/asp.net/BedrockAspNet.mspx

One day in ASP. NET web page Lifecycle

Dino Esposito wintellect

August 2003

Applicable to: Microsoft ASP. NET

Summary: Understand the event model built around ASP. NET web pages and the phases of a web page's transition to HTML. ASP. NET controls the object pipeline during HTTP runtime. The object pipeline first converts the requested URL to a page-class activity instance and then converts it to common HTML text. This article will explore each feature event in the lifecycle of a page, and learn how controls and page writers intervene in it to change its standard behavior. (6 pages)

Content on this page
Introduction
Real page class
Page Lifecycle
Stages of execution
Summary

Introduction

Each request received by Microsoft Internet Information Service (IIS) to a Microsoft ASP. NET page is handed over to the ASP. net http pipeline. The HTTP pipeline consists of a series of hosted objects that process the request in order and complete the conversion from URL to common HTML text. The HTTP pipeline endpoint isHttpruntimeClass. ASP. the net infrastructure creates an instance of this class for each appdomain carried by the auxiliary process (note that this auxiliary process is currently running for each ASP.. Net Applications maintain a different appdomain ).

HttpruntimeSelect a class from the internal poolHttpapplicationObject To process the request. The main task completed by the HTTP application manager is to find the class that will actually process the request. If the request is a. aspx resource, the handler is a page Handler-that is,Page. The associations between resource types and handler types are stored in the configuration file of the application. More accurately, in the machine. config file<Httphandlers>Defines a default set of mappings. However, applications can also customize their own HTTP handler list in the Local Web. config file. The following program line illustrates the code that defines the HTTP handler for. aspx resources.

<add verb="*" path="*.aspx" type="System.Web.UI.PageHandlerFactory"/>

An extension can be associated with a handler class, or more commonly associated with a handler factory class. In all circumstancesHttpapplicationThe object will get an implementationIhttphandlerInterface object. If the associated resource/class is parsed according to the HTTP handler, the returned class will directly implement this interface. If the resource is bound to the handler factory, another step is required. Handler factory implementationIhttphandlerfactoryAndGethandlerMethod returns an ihttphandler-based object.

How can I complete the entire loop and process page requests during HTTP runtime?IhttphandlerThe interface providesProcessrequestMethod. By calling this method for the object representing the requested page, ASP. NET infrastructure starts the corresponding process to generate output for the browser.

Back to Top

Real page class

The type of the HTTP handler for a specific page depends on the URL. When a URL is called for the first time, a new class is built and the class is dynamically compiled into an assembly. The output result of the syntax analysis process used to check the. aspx source is the source code of the class. This class is defined as part of the ASP namespace and assigned a name similar to the original URL. For example, if the URL endpoint is page. aspx, the class name isASP. page_aspx. However, you can also set it through programming.@ PageCommandClassnameAttribute to control the class name.

The base class of the HTTP handler isPage. This class defines the minimum set of methods and attributes shared by all page handlers.PageClass implementationIhttphandlerInterface.

In some cases, the base class of the actual processing program is notPageBut a different class. For example, if the code is hidden, this situation occurs. Code hiding is a development method that encapsulates the Code required by the page into a separate C # or Microsoft Visual Basic. Net class. The page code is a set of event handlers and helper methods used to create the page. Available<SCRIPT runat = Server>Mark to define this code as Inline code, or put it into an external class-code hidden class. The Code hiding class is an inheritedPageBut this type has some additional methods, so it is special. If specified, the Code hiding class is used as the base class of the HTTP handler.

Another scenario is when the application configuration file<Pages>Some have been redefinedPagebasetypeThe HTTP processing program is not based onPage.

<pages PageBaseType="Classes.MyPage, mypage" />

PagebasetypeProperty indicates the type of the base class containing the page handler and the Assembly. Derived fromPageThis class automatically gives the handler a set of custom and extended methods and attributes.

Back to Top

Page Lifecycle

Once the HTTP page handler class is fully determined, ASP. NET callsProcessrequestMethod to process the request. Generally, you do not need to change the implementation method of this method because it is composedPageClass.

This implementation method is called at the beginning.FrameworkinitializeTo create the control tree of the page. This method isTemplatecontrolClass (PageClass itself is derived from the class) a protected Virtual Member. Any handler dynamically generated for. aspx resources is rewritten.Frameworkinitialize. In this method, the complete control tree of the page is built.

Next,ProcessrequestThis page goes through several stages: initialization, loading view status information and sending back data, loading page user code, and executing the sending back server event. Then, the page enters the rendering mode: Collect the updated view status, generate HTML code, and send it to the output console. Finally, uninstall the page and consider that the request has been processed successfully.

In each stage, the page will inspire some Web controls and user-defined code to intercept and process events. Some of these events are dedicated to embedded controls, so they cannot be processed at the. aspx code level.

If the Page wants to process an event, it should explicitly register the corresponding handler. However, to be backward compatible with earlier Visual Basic programming styles, ASP. NET also supports an implicit event suspension form. By default, the page will try to match the specific method name with the event. If a matching method is found, the method is considered as the event handler. ASP. NET provides specific identification of six method names. They arePage_init,Page_load,Page_databind,Page_prerenderAndPage_unload. These methods are treatedPageClass. During HTTP runtime, these methods are automatically bound to page events, so that developers do not have to write the required bonding code. For examplePage_loadMethod andLoadEvent binding, just as you have written the following code.

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

This function automatically identifies special names@ PageCommandAutoeventwireupProperty Control. If this attribute is set to false, any application that wants to process an event needs to explicitly connect to the page event. If the page does not use the automatic event Association function, you do not need to perform any additional operations to match the names and events, thus improving the performance. Note that all Microsoft Visual Studio. NET projects are disabled when they are created.AutoeventwireupAttribute. However, this property is set to true by default, meaningPage_loadMethods are identified and bound to related events.

The page execution process includes a series of stages listed in the following table, and features application-level events and/or protected and Rewritable methods.

Table 1. Key events in ASP. NET page Lifecycle

Phase Page events Rewritable Method

Page Initialization

Init

Load view status

Loadviewstate

Process the returned data

ImplementationIpostbackdatahandlerTheLoadpostdataMethod

Load page

Load

Send a change notification

ImplementationIpostbackdatahandlerTheRaisepostdatachangedeventMethod

Handle sending back events

Any sending event defined by the Control

ImplementedIpostbackeventhandlerTheRaisepostbackeventMethod

Page pre-rendering stage

Prerender

Save view status

Saveviewstate

Rendering page

Render

Uninstall page

Unload

At the page level, some stages listed above are invisible and only affect server control writers andPageThe developer of the derived class. The activity signal sent from the page to the outside world only includesInit,Load,Prerender,UnloadAnd all the sending events defined by embedded controls.

Back to Top

Stages of execution

The first phase in the page lifecycle is initialization. The mark of this stage isInitEvent. After the control tree of the page is successfully created, this event is triggered for the application. In other words, whenInitWhen an event occurs, all controls statically declared in the. aspx source file are instantiated and Their default values are obtained. Controls can be suspendedInitEvents to initialize any settings required for the lifecycle of incoming Web requests. For example, the control can load an external template file or set the event handler. Note that no view status information is available.

After initialization, the page framework immediately loads the view status of the page. The view status is a set of name/value pairs. Controls and pages can store any information that must always be valid for all Web requests. View status indicates the call context of the page. Generally, it contains the status of each control when the page was last processed on the server. When a page is requested for the first time in a session, the view status is empty. By default, the view status is stored in a hidden field, which is automatically added to the page. The field name is_ Viewstate. RewriteLoadviewstateMethod (ControlA protected and Rewritable method of the class) component developers can control how to restore the view state and how to map its content to the internal state.

Some methods (suchLoadpagestatefrompersistencemediumAnd its relativeSavepagestatetopersistencemediumCan be used to load the view status and save it to another storage medium (such as a session, database, or server-side file. AndLoadviewstateDifferent, the above method only derives fromPageCan be used only in each class.

Once the view status is restored, the status of each control in the page tree is the same as that when the browser last presents the page. The next step is to update the status of these controls to add changes to the client. In the sending and processing phase, each control has the opportunity to update its status to accurately reflect the status of corresponding HTML elements on the client. For example, a serverTextboxThe HTML element corresponding to the control is<Input type = text>. In the data re-sending phase,TextboxThe control retrieves the current value marked with <input> and refresh its internal status. Each control extracts the corresponding values from the sent data and updates some of its attributes.TextboxControl will update itsTextAttribute, andCheckboxControl will refresh itsCheckedAttribute. The matching relationship between the Server Control and HTML elements is determined by the IDs of the two.

At the end of the sending and processing stage, all controls on the page update the original status based on the changes entered on the client. In this caseLoadEvent.

If a sensitive property is modified when two different requests are processed, some controls on the page may need to complete some tasks. For example, if the text of a text box control is modified on the clientTextchangedEvent. If one or more properties of the control are modified using the value from the client, each control can decide to trigger an appropriate event. If these changes are critical for controls, these controls implementIpostbackdatahandlerInterface, inLoadTheLoadpostdataMethod. By writingLoadpostdataMethod Code. A control can check whether any key changes have occurred since the last request and trigger its own change events.

The key event in the page lifecycle is that it is called to execute the server-side code associated with an event triggered on the client. When you click a button, the page returns data. The set of sent values contains the ID of the button (which starts the entire operation. If the control is known to implementIpostbackeventhandlerInterface (Button and link button will implement this interface), the page Framework callsRaisepostbackeventMethod. The operation performed by this method depends on the type of the corresponding control. This method is used to search for buttons and links.ClickEvent handler and run related delegation.

After processing the send-back event, the page is ready for rendering. The mark of this stage isPrerenderEvent. Each control can take advantage of this opportunity to execute any last update operations that need to be completed one minute before the view State is saved and the output result is displayed. The next status isSaveviewstateIn this status, all controls and pages can refresh their ownViewstateSet content. The obtained view status can be serialized, hashed, base64 encoded, and associated with the _ viewstate hidden field.

RewriteRenderTo change the rendering mechanism of each control. This method gets an HTML writer object and uses this object to aggregate all the HTML text generated for this control.PageClassRenderThe default method includes recursive calls to all member controls. For each control, the page callsRenderMethod and put the HTML output into the cache.

The final survival mark of a page isUnloadEvent, which occurs before the Page Object is removed. In this event, you should release any key resources (such as files, graphical objects, and database connections) that may be occupied ).

Finally, after this event, the browser receives the HTTP response packet and displays the page.

Back to Top

Summary

The ASP. NET page object model is particularly innovative because of the use of the event mechanism. Web pages are composed of various controls, which form a rich HTML-based user interface and interact with users through events. Creating an event model in the context of a Web application is a very challenging task. Surprisingly, the server-side code can be used to process events generated by the client, and the output of this method seems to be the same as the HTML page, but it has been modified properly.

To master this model, it is important to understand the different stages in the page lifecycle and how to instantiate and use page objects during HTTP runtime.

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.