Ajax. Net-pagerequestmanager object

Source: Internet
Author: User
The scriptmanager and updatepanel controls can implement asynchronous communication between the client and the server. To further control asynchronous operations, we need to further study the pagereqeustmanager class.
Pagerequestmanager is a client class used to coordinate scriptmanager and updatepanel controls and manage asynchronous update operations on the page. Through the pagerequestmanager client instance, we can go deep into the client page lifecycle to perform more detailed operations on the client page.
1. pagerequestmanager instance:
To obtain a pagerequestmanager instance on the client, the page must have a one-person scriptmanager control, and the enablepartialrendering attribute of the scriptmanager control must be set to true.
As long as the page contains a scriptmanager control whose enablepartialrendering attribute is true, a pagerequestmanager instance is automatically created on the page. Program You do not need to create your own pagerequestmanager instance.
Obtain the pagerequestmanager instance Code :
VaR PRM = SYS. webforms. pagerequestmanager. getinstance ();
Attribute PRM. get_isinasyncpostback (): Determines whether an asynchronous delivery is in progress.
Method PRM. abortpostback (): Cancels an asynchronous sending request in progress.
Ii. Client page lifecycle:
The advantage of the pagerequestmanager class is that programmers can go deep into the lifecycle of the client page. To make full use of the functions of the pagerequestmanager class, you must first understand the lifecycle of the asynchronous page.
1. initializerequest:
Triggering time: triggered before an asynchronous request is initiated.
Add event processing code: SYS. webforms. pagerequestmanager. getinstance (). add_initializerequest (initfunc );
Code for event removal: SYS. webforms. pagerequestmanager. getinstance (). remove_initializerequest (initfunc );
Initfunc is the client method to be executed before page initialization. The declaration of this method is:
Function initfunc (sender, argS)
{
// The args data type is initializerequesteventargs.
// Args. get_postbackelement (): gets the element object that initializes asynchronous delivery.
// Args. get_postbackelement (). Id gets the ID of the element object that initializes asynchronous delivery.
// Args. get_postbackelement (). Value gets the value of the element object that initializes asynchronous delivery.
// Args. set_cancel (bool): cancels the initialization of asynchronous delivery, that is, discards This asynchronous delivery.
}
If the asynchronous processing process is slow and the same request is sent again during the asynchronous processing process, the latter's asynchronous Processing request will cancel the unfinished request in the previous step. This is the default asynchronous request priority-"the latter takes precedence ".
We usually use the initailizerequest event to cancel an asynchronous send back (ongoing send back and the send back to be initialized ).
2. beginrequest:
Triggering time: triggered before the asynchronous request Initialization is complete and a request is sent to the server.
Add event processing code: SYS. webforms. pagerequestmanager. getinstance (). add_beginrequest (beginfunc );
Code for event removal: SYS. webforms. pagerequestmanager. getinstance (). remove_beginrequest (beginfunc );
Beginfunc is the client method to be executed before sending a request to the server. The declaration of this method is:
Function beginfunc (sender, argS)
{
// The args data type is beginrequesteventargs.
// Args. get_postbackelement (): gets the element object that initializes asynchronous delivery.
}
We usually set a header in the beginrequest event, or start a vivid notification that the user is processing the request.
3. pageloading:
Trigger time: the asynchronous response has been received and responded by the server, but is triggered before the page is updated.
Add event processing code: SYS. webforms. pagerequestmanager. getinstance (). add_pageloading (loadingfunc );
Code for event removal: SYS. webforms. pagerequestmanager. getinstance (). remove_pageloading (loadingfunc );
Loadingfunc is the client method to be executed before page update. The declaration of this method is:
Function loadingfunc (sender, argS)
{
// The args data type is pageloadingeventargs.
// ARGs indicates the <div> of the updatepanel control whose content is to be updated or deleted.
// Var arr = args. get_panelsdeleting (); obtain the <div>
// Var arr = args. get_panelsupdating (); obtain the <div>
}
4. pageloaded:
Trigger time: triggered after the page area is updated.
Add event processing code: SYS. webforms. pagerequestmanager. getinstance (). add_pageloaded (loadedfunc );
Code for event removal: SYS. webforms. pagerequestmanager. getinstance (). remove_pageloaded (loadedfunc );
Loadedfunc is the client method to be executed after page update. The declaration of this method is:
Function loadedfunc (sender, argS)
{
// The args data type is pageloadedeventargs.
// ARGs indicates the updatepanel control that is updated or created. <div>
// Var arr = args. get_panelsupdated (); obtain the <div>
// Var arr = args. get_panelscreated (); obtain the <div>
}
5. endrequest:
Triggering time: the endrequest event is triggered after the delivery request is processed.
Add event processing code: SYS. webforms. pagerequestmanager. getinstance (). add_endrequest (endfunc );
Code for event removal: SYS. webforms. pagerequestmanager. getinstance (). remove_endrequest (endfunc );
Endfunc is the client method executed after the page request is complete. The declaration of this method is:
Function endrequest (sender, argS)
{
// The data type of argS is endrequesteventargs.
// Var err = args. get_error (): determines whether an error has occurred and obtains the error object.
// Var em = args. get_error (). Message: gets the error message.
// Args. set_errorhandled (true): the setting error has been handled.
// Var GM = args. get_errorhandled (): determines whether the error is handled.
// When an exception occurs in an asynchronous request, if the programmer does not capture and process the request, the pagerequestmanager object will pop up the exception information in a dialog box. If the programmer wants to write the error handling code by himself, rather than by the pagerequestmanager object. Then the programmer can get the error information through the args. get_error (). Message attribute, write the exception handling code, and finally remember to execute args. set_errorhandled (true ). This prevents exceptions from returning to the pagerequestmanager object. The specific usage will be described in detail later.
}
Iii. cases:
1. asynchronous delivery priority-the latter has a higher priority than the former:
If it takes a long time to process asynchronous sending back, the client will generate the second asynchronous sending back in the Process of processing the first sending back, after that, the first sent back to the cancellation will be triggered.
There are two asynchronous buttons on the page to generate asynchronous send-back. To prolong the server's processing time, I used threads to sleep for 10 and 5 seconds in the server click events of the two buttons respectively, then, enter the processing result in the lblinfo tag.

<Asp: button id = "btnlong" runat = "server" text = "responds 10 seconds later" onclick = "btnlong_click"/>
<Asp: button id = "btnshort" runat = "server" text = "respond after 5 seconds" onclick = "btnshort_click"/>
<Asp: scriptmanager id = "scriptmanager1" runat = "server">
</ASP: scriptmanager>
<Asp: updatepanel id = "updatepanel1" runat = "server">
<Contenttemplate>
<Asp: Label id = "lblinfo" runat = "server" backcolor = "# c0c0ff" width = "100%"> </ASP: Label>
</Contenttemplate>
<Triggers>
<Asp: asyncpostbacktrigger controlid = "btnlong" eventname = "click"/>
<Asp: asyncpostbacktrigger controlid = "btnshort" eventname = "click"/>
</Triggers>
</ASP: updatepanel>
To make it clear that the next step triggers the cancellation of the previous step, I added the beginrequest event processing code to the pagerequestmanager object and displayed the request sender on the page before sending the request.
VaR PRM = SYS. webforms. pagerequestmanager. getinstance ();
PRM. add_beginrequest (beginr );
Function beginr (sender, argS)
{
VaR d = $ get ("lblinfo ");
VaR T = args. get_postbackelement (). value;
D. innerhtml = "processing the same" + T + "-triggered delivery ";
}
Server code:
Protected void page_load (Object sender, eventargs E)
{
Scriptmanager1.registerasyncpostbackcontrol (this. btnlong );
Scriptmanager1.registerasyncpostbackcontrol (this. btnshort );
}
Protected void btnlong_click (Object sender, eventargs E)
{
System. Threading. thread. Sleep (10000 );
Lblinfo. Text = (button) sender). Text + "generated response ";
}
Protected void btnshort_click (Object sender, eventargs E)
{
System. Threading. thread. Sleep (5000 );
Lblinfo. Text = (button) sender). Text + "generated response ";
}
Effect: When you click the "generate response after 10 seconds" button, lblinfo displays the "sending back triggered by response after the same 10 seconds ", if you click the "generate response after 5 seconds" button again, lblinfo will be displayed as "sending a response after 5 seconds of processing ". At this time, the first sent back is canceled. Wait for 5 and the page will display "response generated after 5 seconds". The server response for the first sent back is not displayed.

2. Cancel asynchronous delivery:
Two types of asynchronous delivery cancellation are available:
A. Cancel self-executed asynchronous delivery-cancel by calling the abortpostback () method of the pagerequestmanager object.
B. Cancel the newly generated innovation point delivery-cancel by setting the cancel attribute of the initializerequesteventargs object to true.

The following is an interface for querying car information. To prolong the server's processing time, I added a sleep time of 6 seconds to the query button.
When you click query, I added a <div> to prompt that the user request is being processed, and added a "cancel" button in <div> to prevent the user from doing so, when you click "cancel", you can stop asynchronous processing on the server.

The following interface is displayed after the server completes asynchronous request processing.

If the asynchronous request is not processed by the server, you can click the "query" button to prevent the first sent message from being pushed back and add the prompt information to the interface.


Interface Design:

The HTML code is as follows:
<Asp: scriptmanager id = "scriptmanager1" runat = "server" asyncpostbackerrormessage = "this is a small custom exception">
</ASP: scriptmanager>
<Asp: dropdownlist id = "DDL" runat = "server" performanceid = "sqlperformance1" datatextfield = "prod_name"
Datavaluefield = "prod_code" width = "194px">
</ASP: dropdownlist>
<Asp: button id = "button1" runat = "server" text = "query" onclick = "button#click"/>
<Asp: sqldatasource id = "sqldatasource1" runat = "server" connectionstring = "<% $ connectionstrings: mydbconnectionstring %>"
Selectcommand = "select [prod_code], [prod_name] from [productor]"> </ASP: sqldatasource>
<Asp: updatepanel id = "updatepanel1" runat = "server">
<Contenttemplate>
<Div id = "divinfo" style = "background-color: # ff99ff; display: none;">
<Asp: button id = "btncancel" runat = "server" text = "cancel"/> </div>
<Br/>
<Asp: gridview id = "list" runat = "server" width = "100%" performanceid = "sqlperformance2">
</ASP: gridview>
<Asp: sqldatasource id = "sqldatasource2" runat = "server">

</ASP: sqldatasource>
</Contenttemplate>
<Triggers>
<Asp: asyncpostbacktrigger controlid = "button1" eventname = "click"/>
</Triggers>
</ASP: updatepanel>

The CS code is as follows:
Protected void page_load (Object sender, eventargs E)
{
Scriptmanager1.registerasyncpostbackcontrol (this. button1 );
}
Protected void button#click (Object sender, eventargs E)
{
System. Threading. thread. Sleep (6000 );
String STR = webconfigurationmanager. connectionstrings ["mydbconnectionstring"]. tostring ();
Sqldatasource2.connectionstring = STR;
Sqldatasource2.selectcommand = "select car. IDs, car. Name, car. Price, brand. brand_name, prod_code from car join brand on car. Brand = brand_code where prod_code = @ P ";
Sqldatasource2.selectparameters. Clear ();
Sqldatasource2.selectparameters. Add ("P", DDL. selectedvalue );
Sqldatasource2.select (datasourceselectarguments. Empty );
}

Implementation of client JS Code:
VaR PRM = SYS. webforms. pagerequestmanager. getinstance (); // gets an instance of the pagerequestmanager object
PRM. add_initializerequest (init); // Add an object initialization event handler
Function Init (sender, argS) // event handler
{
// If the "cancel" button is clicked during asynchronous processing, the asynchronous processing being processed will be aborted.
If (PRM. get_isinasyncpostback () & args. get_postbackelement (). Id = "btncancel ")
{
PRM. abortpostback (); // abort asynchronous Processing
}
// If another "query" button is clicked during asynchronous processing, the new request will be canceled.
Else if (PRM. get_isinasyncpostback () & args. get_postbackelement (). Id = "button1 ")
{
Args. set_cancel (true); // cancel a new request
VaR d = $ get ("divinfo ");
D. style. Display = "";
D. innerhtml + = "<br> the request is still in progress. Please wait ";
}
// If no asynchronous processing is in progress and the user clicks the "query" button, it will show "The request is in progress. Please wait"
Else if (! PRM. get_isinasyncpostback () & args. get_postbackelement (). Id = "button1 ")
{
VaR d = $ get ("divinfo ");
D. style. Display = "";
D. innerhtml + = "<br> the request is in progress. Please wait ";
}
}

3. custom error handling for asynchronous requests.
If an error occurs during asynchronous request processing, a browser dialog box is displayed by default to indicate the error message. Sometimes we don't want to use this default Exception Handling interface. What should we do?
Steps:
A. Compile the scriptmanager object's server-side event scriptmanagerpolicasyncpostbackerror code and assign the captured error information to the asyncpostbackerrormessage attribute of the scriptmanager object.
B. Add the endrequest event handler OF THE pagerequestmanager object. In the processing program, argS. get_error (). message is used to retrieve the running error information. Then, the error message is displayed in the specified <div>.
C. Use set_errorhandled (true) to mark the error object as being processed to prevent the error object from continuing to bubble to the browser.
Interface:


HTML code:
<Asp: scriptmanager id = "scriptmanager1" runat = "server" onasyncpostbackerror = "scriptmanagerpolicasyncpostbackerror">
</ASP: scriptmanager>
<Br/>
<Asp: button id = "btnok" runat = "server" onclick = "btnok_click" text = "successfully sent"/>
<Asp: button id = "btnerror" runat = "server" onclick = "btnerror_click" text = "failed to send"/> </div>
<Asp: updatepanel id = "updatepanel1" runat = "server">
<Contenttemplate>
<Asp: Label id = "lblinfo" runat = "server" backcolor = "# c0c0ff" width = "100%"> </ASP: Label>
</Contenttemplate>
<Triggers>
<Asp: asyncpostbacktrigger controlid = "btnerror" eventname = "click"/>
<Asp: asyncpostbacktrigger controlid = "btnok" eventname = "click"/>
</Triggers>
</ASP: updatepanel>
CS code:
Protected void page_load (Object sender, eventargs E)
{
Scriptmanager1.registerasyncpostbackcontrol (btnok );
Scriptmanager1.registerasyncpostbackcontrol (btnerror );
}
Protected void btnok_click (Object sender, eventargs E)
{
Lblinfo. Text = "asynchronous delivery successful ";
}
Protected void btnerror_click (Object sender, eventargs E)
{
Exception EX = new exception ("this is a Custom User exception information ");
Throw ex;
}
Protected void scriptmanagerpolicasyncpostbackerror (Object sender, asyncpostbackerroreventargs E)
{
Scriptmanager1.asyncpostbackerrormessage + = E. Exception. message;
}
Client JS Code:
VaR PRM = SYS. webforms. pagerequestmanager. getinstance ();
PRM. add_endrequest (endfunc );
Function endfunc (sender, argS)
{
If (ARGs. get_error ()! = NULL)
{
Var em = args. get_error (). message;
Args. set_errorhandled (true );
$ Get ("lblinfo"). innerhtml = em;
}
}

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.