The "ASP. NET Base" Page class and callback technology

Source: Internet
Author: User
Tags key string

The page class has a IsPostBack property that indicates whether the current page is loaded for the first time or a server event that responds to a control on the page that causes a postback.

1.asp.net the declaration period of a page

When you run an ASP. NET page, it goes through a declaration cycle in which a series of actions are invoked to invoke a series of methods. Understanding the life cycle of an ASP. NET page is important for controlling the rendering and behavior of controls on the page precisely.

In general, a regular page goes through several life cycle stages:

Stage Description
Page request Page requests occur before the page life cycle begins. When a user requests a page, ASP. NET determines whether the page needs to be parsed and compiled (thereby starting the life cycle of the page), or whether the cached version of the page can be sent in response without running the page.
Begin In the start phase, page properties, such as Request and Response, are set. At this stage, the page also determines whether the request is a postback request or a new request, and sets the IsPostBack property. Also, during the start phase, the UICulture property of the page is set.
Page initialization During page initialization, the controls in the page can be used, and the UniqueID property of each control is set. In addition, any theme will be applied to the page. If the current request is a postback request, the postback data has not yet been loaded, and the control property value has not been restored to the value in view state.
Load During load, if the current request is a postback request, the control property will be loaded with information recovered from view state and control state.
Verify During validation, the Validate method for all validator controls is invoked, and this method sets the IsValid properties for each validator control and page.
Postback event handling If the request is a postback request, all event handlers are called.
Present During rendering, view state is saved to the page, and then the page calls each control to provide its rendered output to the outputstream of the page's Response property.
Unloading The uninstallation is invoked when the page is fully rendered, when the page is sent to the client and ready to be discarded. At this point, the page properties (such as Response and Request) are unloaded and cleanup is performed.



In the life cycle of a page, there are typically the following events:

Page Events Typical use
Page_PreInit Use the IsPostBack property to determine whether the page is processed for the first time.
Creates or re-creates a dynamic control.
Dynamically set the master page.
Dynamically sets the Theme property.
Reads or sets the profile property value.
Note: If the request is a postback request, the value of the control has not been restored from view state. If a control property is set at this stage, its value may be overwritten in the next phase.
Page_Init Reads or initializes a control property.
Page_Load Read and update control properties.
Control Events To perform application-specific processing:
If the page contains validator controls, check the IsValid properties of the page and individual validation controls before performing any processing.
Handles a specific event, such as the Click event of a Button control.
Page_PreRender Make the last change to the contents of the page.
Page_Unload Perform the final cleanup work, which may include:
Close open files and database connections.
Complete log records or other request-specific tasks.


It is important to note that each ASP. NET control also has a life cycle similar to ASP. If an ASPX page contains an ASP. NET server control, the method of the control is called when the page's method is called.

In addition, the Web application is stateless. Each time a new page is requested or the page server is refreshed, a new instance of the current page is created, which means that the previous information for the page cannot be obtained, and if this is really necessary, an additional mechanism is required.

2. Dynamic output JavaScript script

Response.Write ("<script language= ' JavaScript ' >alert ('" + DateTime.Now.ToString () + "') </script>");

This will bring up a dialog box each time you run the Home.aspx page.

The output of the JavaScript code is outside the
There is a ClientScript property in the Page class, which is an instance of ClientScriptManager, which is new in asp.net2.0. There are several common methods for ClientScriptManager:
RegisterClientScriptBlock Method: Registers the client script with the Page object.
RegisterStartupScript Method: Registers the startup script with the Page object.
The ClientScriptManager class uniquely identifies a script by key string and type. A script with the same type of key and type is known as the same script.

if (! Clientscript.isclientscriptblockregistered (this. GetType (), "Clientscriptblock")) {Clientscript.registerclientscriptblock (this. GetType (), "Clientscriptblock", "<script language= ' JavaScript ' >alert (' Clientscriptblock ') </script>");  } if (! Clientscript.isstartupscriptregistered (this. GetType (), "Startupscript"))  {   Clientscript.registerstartupscript (this. GetType (), "Startupscript", "<script language= ' JavaScript ' >alert (' startupscript ') </script>");  }

When you execute the page, you will get a popup of two prompt windows

The above two methods output JavaScript scripts are within the <form></form> tag, will not break the structure of the article, and the JavaScript script code block that the RegisterClientScriptBlock method outputs is close to the start tag of the <form> tag, The JavaScript script code block output by the RegisterStartupScript method is close to the end tag of the <form> tag, which is advantageous for controlling the time of dynamically added client script.

3. Callback Technology (CallBack)

In ASP. Client-Server interaction defaults to full page commits, at which point the client submits the data from the current page form (including some automatically generated hidden fields) to the server side, the server instantiates an instance of the current page class to respond to the request, and then sends the contents of the entire page back to the client, which is handled The results have no effect, but this method increases the network data transmission burden, increases the workload of the server, and the user needs to wait for the final processing results. If we want to have such a function, when the user completed the user name to check whether the user name already exists in the server database, if there is a hint that already exists this user name, if not exist to prompt the user this user name is available, in this case, in fact, only need to pass a user name as a parameter, The above approach requires the submission of the entire form, a bit of a fuss. There are three ways to solve the above problem: pure JavaScript Implementation, Microsoft Ajax Class Library implementation is also useful AJAXPRO implementation.

Here I'm talking about another implementation: through callback techniques.

Creating a Web page that implements callback technology is similar to a normal ASP. NET, except that you need to do the following special work:
(1) Let the current page implement the ICallbackEventHandler interface, this interface defines two methods: the string GetCallbackResult () method and the void RaiseCallbackEvent (string Eventargument) method. where the GetCallbackResult () method is used to return the result of a callback event that targets a control, the RaiseCallbackEvent () method is used to handle callback events that target the control.
(2) provides three JavaScript client script functions for the current page. A JavaScript function is used to perform the actual request to the server, where a string type parameter can be supplied to the server side, and another JavaScript function is used to receive the string type result returned after the server-side method is executed and to process the result There is also a helper function that executes a request to the server, which is automatically generated by ASP. When you get a reference to the method through the GetCallbackEventReference () method in server code.
Let me tell you a detailed example of how to use callbacks to create a register with Dreamweaver. ASPX page with the following code:

<%@ page language= "C #" contenttype= "text/html" responseencoding= "gb2312"%><%@ Implements interface= " System.Web.UI.ICallbackEventHandler "%><%@ Import namespace=" System.Text "%><! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd "><span id= "message" ></span></td></tr><tr><td> password </td><td>< Input type= "password" size= "ten" maxlength= "id=" Txtpwd "/></td></tr></table></form>" </body>

The above page has been detailed enough to look at, but there are a few things to note:

[1]

<%@ Implements interface= "System.Web.UI.ICallbackEventHandler"%>

This sentence indicates that the current page implements the ICallbackEventHandler interface, if the page and code separation mode, the background CS code should be:

Public partial class Register:System.Web.UI.Page, Icallbackeventhandler{//cs code}

[2]

<input type= "text" size= "ten" maxlength= "id=" txtUserName "onblur=" Callservermethod (txtusername.value,null) "/ >

Here is a onblur= "Callservermethod (txtusername.value,null), which means that when the user Name text box loses focus, Callservermethod This client method is fired, This client-side method is generated dynamically by ASP.

[3]

Csm. GetCallbackEventReference (This, "args", "Success", "", "Error", false);

The "Success" and "error" in each of the client's JavaScript functions, which can be seen in code, where "Success" represents the client method name to execute after the server-side method succeeds, "Error" Represents the client method name that is called when the call server-side method fails.

Source: http://zhoufoxcn.blog.51cto.com/792419/166784

The "ASP. NET Base" Page class and callback technology

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.