Document directory
- Page Lifecycle
- Simple page example
- Public appearance example
By default,Page ControllerThe concepts described in the schema are implemented in ASP. NET. ASP. the net page framework implements these concepts by automatically capturing events on the client, transmitting them to the server, and calling appropriate methods, it is invisible to the implementer. The page controller is scalable because it exposes various events at specific points in the lifecycle (see "Page lifecycle" after this mode). Therefore, operations related to the application can be run as appropriate.
For example, assume that the user is interacting with a web form page containing a button server control (see "simple page example" after this mode "). When you click the button control, an event is sent to the server as the HTTP shipping content, where ASP. the net page framework will explain the shipping information and associate the events that occur with appropriate event handlers. The framework automatically calls the appropriate event handler for this button as part of the normal processing of the framework. Therefore, you no longer need to implement this function. In addition, you can use a built-in controller, or you can use your own custom controller to replace the built-in Controller (seeFront Controller).
Page Lifecycle
The following lists the most common stages in the page lifecycle in the order of occurrence. It also includes the specific events that are triggered and some typical operations that may be performed at each stage during request processing:
| • |
ASP. NETPage framework initialization (event:Init). This is the first step in the lifecycle. This step initializes the ASP. NET Runtime Library to prepare for the response request. |
| • |
User code initialization (event:Load). You should execute common tasks related to the application, such as opening the database connection when the page controller triggers the load event. You can assume that after the load event is triggered, the server control has been created and initialized, the status has been restored, and the Form Control reflects the client changes. [Reilly02] |
| • |
Application-related event handling. In this phase, you should perform application-related processing to respond to events triggered by the Controller. . |
| • |
Clear (event:Unload). The page has been generated and can be discarded now. You should close any database connection opened by the load event and discard any unnecessary objects. After the connection object is recycled as garbage, Microsoft ?. Net Framework will automatically close the database connection. However, you have no control over when to recycle garbage. Therefore, it is a good practice to explicitly close the database connection pool to make full use of the database connection pool. |
Note:Several page processing stages are not listed here. However, these stages are not used for most page processing situations.
Simple page example
The first example is a simple page that accepts input from the user and displays the input on the screen. This example illustrates the event-driven model used by ASP. NET to implement server controls.
Figure1:Simple page
After you type his or her name and click "Click here", the name will appear under the button, as shown in figure 2.
Figure2:Display a simple page of user input
In ASP. NET web pages, user interface programming is divided into two different parts: visual components (or views) and logic combining models and controllers. This division separates the visible part (view) of the page from the code (model and controller) behind the page that interacts with the page.
A visual element is called a web form page. This page consists of files that contain static html server controls or ASP. NET Server controls (or both controls. In this example, the web form page is named simplepage. aspx, which consists of the following code:
<%@ Page language="c#" Codebehind="SimplePage.aspx.cs" AutoEventWireup="false" Inherits="SimplePage" %> <HTML> <body> <form id="Form1" runat="server"> Name:<asp:textbox id="name" runat="server" /> <p /> <asp:button id="MyButton" text="Click Here" OnClick="SubmitBtn_Click" runat="server" /> <p /> <span id="mySpan" runat="server"></span> </form> </body> </HTML>
The web form page logic consists of the Code created to interact with the form. The programming logic is placed in a file separated from the user interface file. This file is called "code hiding". The file name is simplepage. aspx. CS:
using System; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; public class SimplePage : System.Web.UI.Page { protected System.Web.UI.WebControls.TextBox name; protected System.Web.UI.WebControls.Button MyButton; protected System.Web.UI.HtmlControls.HtmlGenericControl mySpan; public void SubmitBtn_Click(Object sender, EventArgs e) { mySpan.InnerHtml = "Hello, " + name.Text + "."; } }
The purpose of this Code is to notify the page Controller: when a user clicks the button, a request is sent to the server and executedSubmitbtn_clickFunction.
This implementation shows how easy it is to connect to the events provided by the Controller. It also shows that the code written in this way is easier to understand, because the application logic is not combined with the low-level code used to manage event scheduling.
Public appearance example
The following example uses a typical Implementation Policy of the page controller to display banners with dynamic content, this Banner displays the email addresses of verified users on each page of the application (this address is retrieved from the database ).
The base classes inherited by all page objects in the site contain public implementations. Figure 3 shows a webpage on the site.
Figure3:Display banners with Dynamic Content
Each page in the site is responsible for displaying its own content, while the base class is responsible for displaying the header information. Because each page is inherited from the base class, they all have the same function.
This implementation usesTemplate Method. This mode defines an algorithm framework in an operation and submits some steps to the subclass for completion.Template MethodThe subclass is allowed to redefine certain steps of the Algorithm without changing the structure of the algorithm. [Gamma95]
SetTemplate MethodTo solve this problem, you need to move the public code from each page to a base class. This ensures that the public code is put in one place and easy to maintain. In this example, the base class is namedBasepageAnd responsiblePage_loadMethod connectionLoadEvent. AndBasepageAfter the related work (that is, retrieving the user's email address from the database and setting the site name) is completed,Page_loadThe function will callPageloadevent. Subclass implementationPageloadeventTo execute their own specificLoadFunction. Figure 4 shows the structure of the solution.
Figure4:Structure of code hiding page implementation
When a webpage is requested, the ASP. NET Runtime Library will triggerLoadEvent, which is called againBasepageOfPage_loadMethod.BasepageMethod to retrieve the required data, and then callPageloadeventTo perform any page-related loading. Figure 5 shows the page request sequence.
Figure5:Page request sequence
In this way, the public function is implemented, the page does not need to set the header information, and the whole site can be easily changed. If the header information is rendered and the initialization code is not included in a file, you must modify all the files that contain the Code related to the header information.
Basepage. CS
The basic code implements the following functions:
| • |
Connect the load eventPage_loadMethod to initialize the request. |
| • |
Retrieve the authenticated user name from the request context and useDatabasegatewayClass to search for the user's records in the database. This code willEmailThe email address assigned by the tag to the user. |
| • |
Allocate site namesSitenameLabel. |
| • |
CallPageloadeventMethod, which can be implemented by the derived class for any page-related loading. |
Note:: It is bestBasepageClass is defined as an abstract class, because it can force the implementer to providePageloadevent. But in Microsoft Visual Studio? . Net, it is impossible to define this base class as an abstract class. Instead, this class provides the default implementation that can be overwritten by the derived class.
Using system; using system. web. ui; using system. web. UI. webcontrols; public class basepage: Page {protected label email; protected label sitename; virtual protected void pageloadevent (Object sender, system. eventargs e) {} protected void page_load (Object sender, system. eventargs e) {If (! Ispostback) {string name = context. user. identity. name; email. TEXT = databasegateway. retrieveaddress (name); sitename. TEXT = "micro-site"; pageloadevent (sender, e) ;}# region web form designer generated code override protected void oninit (eventargs E) {/// // codegen: This call is ASP.. NET web form designer. // Initializecomponent (); base. oninit (e) ;}/// <summary> /// the designer supports the required methods-do not use the code editor to modify the content of this method. /// </Summary> private void initializecomponent () {This. Load + = new system. eventhandler (this. page_load);} # endregion}
Basepage. inc
You must not only provide a public base class for the logic code behind the page, but also a public file used to save the rendering code of the view or UI. This code is included in each. ASPX page. This html file is not used for independent display. By using a public file, you can make changes in one place and spread these changes to all webpages including the file. The following sample code shows the public file in this example. The file name is basepage. Inc:
<Table width = "100%" cellspacing = "0" cellpadding = "0"> <tr> <TD align = "right" bgcolor = "#9c0001" cellspacing = "0" cellpadding = "0" width = "100%" Height = "20"> <font size = "2" color = "# ffffff"> welcome: <asp: Label id = "email" runat = "server"> username </ASP: Label> & nbsp; </font> </TD> </tr> <TD align = "right" width = "100%" bgcolor = "# d3c9c7" Height = "70"> <font size = "6" color = "# ffffff"> <asp: label id = "sitename" runat = "server"> micro-site banner </ASP: Label> & nbsp; </font> </TD> </tr> </table>
Databasegateway. CS
This class encapsulates all access to the database from these pages. This isTable Data Gateway[Fowler03] provides the model code for the page in this application.
using System; using System.Collections; using System.Data; using System.Data.SqlClient; public class DatabaseGateway { public static string RetrieveAddress(string name) { String address = null; String selectCmd = String.Format("select * from webuser where (id = '{0}')", name); SqlConnection myConnection = new SqlConnection("server=(local);database=webusers;Trusted_Connection=yes"); SqlDataAdapter myCommand = new SqlDataAdapter(selectCmd, myConnection); DataSet ds = new DataSet(); myCommand.Fill(ds,"webuser"); if(ds.Tables["webuser"].Rows.Count == 1) { DataRow row = ds.Tables["webuser"].Rows[0]; address = row["address"].ToString(); } return address; } }
Page1.aspx
The following is an example of how to use public functions on the page:
<%@ Page language="c#" Codebehind="Page1.aspx.cs" AutoEventWireup="false" Inherits="Page1" %> <HTML> <HEAD> <title>Page-1</title> </HEAD> <body> <!-- #include virtual="BasePage.inc" --> <form id="Page1" method="post" runat="server">
The following command in the file is used to load the public HTML of the header information:
<!-- #include virtual="BasePage.inc" -->
Page1.aspx. CS
The Code hiding class must beBasepageClass, and then implementPageloadeventTo load the page. In this example, the activity related to the page is to allocate the number 1PagenumberLabel.
using System; using System.Web.UI; using System.Web.UI.WebControls; public class Page1 : BasePage { protected System.Web.UI.WebControls.Label pageNumber; protected override void PageLoadEvent(object sender, System.EventArgs e) { pageNumber.Text = "1"; } } Back to Top
Test considerations
The dependency on the ASP. NET Runtime Library makes it very difficult to implement the test. It is impossible to instantiate classes inherited from system. Web. UI. Page or other types contained in the environment. In this way, it is impossible to perform unit tests on each part of the application. The only way to automatically test this implementation is to generate an HTTP request and then retrieve the HTTP Response to check whether the response is correct. This method is prone to errors because you compare the response text with the expected text.
Back to Top
Result Context
The built-in ASP. NET page controller has the following advantages and disadvantages:
Advantages
| • |
Make full use of the framework functions.The page controller function is built in ASP. NET and can be easily expanded by connecting Specific actions related to the application to events exposed by the Controller. In addition, the code associated with the controller can be easily separated from the model and view code by using the code hiding function. |
| • |
ExplicitURL.The URL entered by the user references the actual webpage in the application. This means that these webpages can be used as bookmarks and entered later. URLs also tend to use fewer parameters to make it easier for users to enter them. |
| • |
Added reusability and reusability.The "public appearance" example shows how you can reuse many pages.BasepageWithout modifyingBasepageClass or HTML file. |
Disadvantages
| • |
You need to change the code.As described in the "public appearance" example, to share a public function, you must modify each page to inherit the newly defined base class insteadSystem. Web. UI. Page.Intercepting FilterThe Mode describes how to add public functions by modifying the web. config file rather than the web page itself. |
| • |
Use inheritance.The "public appearance" example uses inheritance to share multiple webpages. Most programmers who learn object-oriented programming methods will like inheritance at the beginning. However, using inheritance to share implementations often makes it difficult for software to change. If the base class becomes complex due to the condition logic, it is best to introduce the helper class or consider usingFront Controller. |
| • |
Difficult to test.Since the page controller is implemented in ASP. NET, it is difficult to test it separately. To improve testability, you |
The same number of functions should be separated from ASP. NET special code into classes that do not depend on ASP. NET. In this way, you do not have to start the ASP. NET Runtime Library for testing.