Use the ICallbackEventHandler interface to implement client callback

Source: Internet
Author: User

Http://www.cnblogs.com/kokoliu/archive/2009/02/03/916427.html

 

Summary

Based on. net has a lot of Ajax frameworks, and Ajax has become very foolish, and even MS is crazy to say that all Asp. net programmers can write Ajax technology on their resumes. MS's arrogant capital is MS's Asp. net 2.0 Ajax framework. Many Ajax frameworks have indeed brought us a lot of convenience for development, and even simplified Ajax applications to the point where controls are dragged, but this has also led to the abuse of Ajax by many people, as long as you are happy, you just need to set up an UpdatePannel. This has become a habit of many programmers, but you do not know that this is often the opposite effect, increasing the burden on the server.
In the process of writing a program, I do not like to use the Ajax framework for some small Ajax effects. It is obviously unwise to use the Ajax framework for a little effect. Many simple Ajax effects can be easily completed by adding some simple code using the ICallbackEventHandler interface. The following describes how to use the ICallbackEventHandler interface to implement client callback.Check whether the user name is available.

 

Effect

 

Implementation Since it is used ICallbackEventHandlerFirst, let's take a look at the ICallbackEventHandler interface. ICallbackEventHandlerInterface is used to indicate that the control can be used as the target of the callback event of the server. Any control that needs to receive callback events must implement ICallbackEventHandlerInterface. Two methods are required to inherit from this interface. RaiseCallbackEventAnd GetCallbackResult, Where, RaiseCallbackEventUsed to process requests submitted by the client, RaiseCallbackEventeThere is a string type parameter, which is the parameter submitted by the client to the server. While GetCallbackResultThe method returns the processing result of the server to the client.
To implement the callback function, the client must also have a function that sends a callback request to the server. You can use the GetCallbackEventReference method of the ClientScriptManager class to register a callback function on the page. Next let's take a look at the GetCallbackEventReference method in MSDNExplanation in:

Syntax:
Public string GetCallbackEventReference (
Control control,
String argument
String clientCallback
String context
String clientErrorCallback
Bool useAsync
)

Parameters
Control
The server that processes the client callback. This control must implement the ICallbackEventHandler interface and provide the RaiseCallbackEvent method.

Argument sends a parameter from the client script to the server.

ClientCallback
The name of a client event handler. the handler receives the result of a successful server event.

Context
The client script calculated on the client before the callback is started. The result of the script is returned to the client event handler.

ClientErrorCallback
The name of the client-side event handler. the handler receives the result when an error occurs in the server-side event handler.

UseAsync
True indicates synchronous execution callback. false indicates asynchronous execution callback.

Return Value
The name of the client function that calls the client callback.

After learning about the above two points, we will start to implement this function. Modify the page first, inherit ICallbackEventHandlerInterface to make the Page Support callback

Public partial class _ Default: System. Web. UI. Page, ICallbackEventHandler

Then we simulate a list of existing users. Here we use a string array for the sake of simplicity (in fact, it is lazy). Of course, you can also connect to the database to obtain existing users.

String [] UserNames = {"LixingTie", "pig "};

With an existing user, let's implement ICallbackEventHandlerInterface member. First, implement RaiseCallbackEventMethod to process the results submitted by the client. To save RaiseCallbackEventMethod Processing result, I declare a variable CallbackResultTo save.

String CallbackResult = null;
Public void RaiseCallbackEvent (string eventArgument)
{
If (eventArgument = "pig ")
Throw new Exception ("Please do not launch personal attacks! ");
CallbackResult = Array. IndexOf (UserNames, eventArgument )! =-1? "This account has been registered": "unregistered users ";
}

HereRaiseCallbackEventMethod, the user name parameter eventArgument submitted by the client is judged. If the user name is a "pig", an exception is thrown, this is mainly used to test whether client events process errors on the server. If the user submitted by the client is not a "pig", it determines whether the user name already exists (whether the user is in UserNames or is "LixingTie" or "pig ), if yes, the result is "this account has been registered" or "unregistered user ".

Continue to implement ICallbackEventHandlerAnother member of the interface GetCallbackResultTo return the processing result to the client.

Public string GetCallbackResult ()
{
Return CallbackResult;
}

The implementation of this method is relatively simple and simply returnsRaiseCallbackEventMethod Processing resultCallbackResult;

Implemented ICallbackEventHandlerAfter the interface, we need to register a function that sends a callback request to the server in the client. We will implement this step in the Load event on the page.

Protected void Page_Load (object sender, EventArgs e)
{
If (Page. Request. Browser. SupportsXmlHttp)
{
ClientScriptManager cs = Page. ClientScript;
String callbackScript = cs. GetCallbackEventReference (this, "GetClientUserName ()", "OnCallbackCompleted", null, "OnServerError", true );
String callbackScriptMethod = "function CallbackScriptMethod () {" + callbackScript + ";}";
Cs. RegisterClientScriptBlock (this. GetType (), "CallbackScriptMethod", callbackScriptMethod, true );
}
}

First useClientScriptManager cs = Page. ClientScript;To obtainClientScriptManagerReference. ThenGetCallbackEventReferenceRegister the function that sends the callback request,Cs. GetCallbackEventReference (this, "GetClientUserName ()", "OnCallbackCompleted", "", "OnServerError", true );

Parameter 1This indicates that the control for processing the client callback is the current page.

Parameter 2"GetClientUserName ()" is a javascript function on the page. This function returns the user name entered in the TextBox. the user name is submitted to the server for judgment. GetClientUserName () the specific content of the function will be added below.

  Parameter 3"OnCallbackCompleted" indicates that the javascript function that receives the server-side event processing result is OnCallbackCompleted.

  Parameter 4Null. this parameter is not required for this instance, so a null value is given. For specific functions of this parameter, see the description of MSDN above.

  Parameter 5"OnServerError", this parameter specifies that when the server handles an error, the client's javascript function OnServerError () will receive and process the error information. In this example, when the user inputs "pig" in the TextBox, the server throws an error and calls the client function OnServerError () to handle the error and display it.

  Parameter 6True indicates synchronous execution of the callback.

GetCallbackEventReferenceThe function returns a string type callback request script based on the parameter. We save this script in the callbackScript variable.
String callbackScriptMethod = "function CallbackScriptMethod () {" + callbackScript + ";}";This statement concatenates a javascript script named CallbackScriptMethod and places the callback request script in this function. After this is done, callback can be triggered through the CallbackScriptMethod () function in javascript.

Cs. RegisterClientScriptBlock (this. GetType (), "CallbackScriptMethod", callbackScriptMethod, true );This statement calls the callback function.CallbackScriptMethod ()Send to the client.

AsIf (Page. Request. Browser. SupportsXmlHttp)This statement is used to check whether the client browser is XmlHttp. Because the callback function uses XmlHttp, this function is unavailable in browsers that do not support XmlHttp.

Now, the server logic is complete. The complete background code is as follows:

Code click + expand
Using System;
Using System. Data;
Using System. Configuration;
Using System. Web;
Using System. Web. Security;
Using System. Web. UI;
Using System. Web. UI. WebControls;
Using System. Web. UI. WebControls. WebParts;
Using System. Web. UI. HtmlControls;

Public partial class _ Default: System. Web. UI. Page, ICallbackEventHandler
{
String CallbackResult = null;
String [] UserNames = {"LixingTie", "pig "};

Protected void Page_Load (object sender, EventArgs e)
{
ClientScriptManager cs = Page. ClientScript;
If (Page. Request. Browser. SupportsXmlHttp)
{
String callbackScript = cs. GetCallbackEventReference (this, "GetClientUserName ()", "OnCallbackCompleted", null, "OnServerError", true );
String callbackScriptMethod = "function CallbackScriptMethod () {" + callbackScript + ";}";
Cs. RegisterClientScriptBlock (this. GetType (), "CallbackScriptMethod", callbackScriptMethod, true );
}
Else
{
Cs. RegisterStartupScript (this. GetType (), "SupportsXmlHttp", "alert ('your browser does not support XmlHttp and cannot use the callback function! ') ", True );
}
}

Public string GetCallbackResult ()
{
Return CallbackResult;
}

Public void RaiseCallbackEvent (string eventArgument)
{
If (eventArgument = "pig ")
Throw new Exception ("Please do not launch personal attacks! ");
CallbackResult = Array. IndexOf (UserNames, eventArgument )! =-1? "This account has been registered": "unregistered users ";
}
}

Now, let's implement the page interface and client javascript. The page content is very simple. It is a TextBox used to enter the user name, an HTML Button that initiates the callback, and a SPAN that displays information.

<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: TextBox ID = "ClientUserName" runat = "server"> </asp: TextBox>
<Input id = "CheckBtn" type = "button" value = "check account" onclick = "CheckUserName ();"/>
<Span id = "message" style = "color: Red;"> </span>
</Div>
</Form>
</Body>

Now let's complete the javascript used in the server code. The Code is as follows:

<Script language = "javascript" type = "text/javascript">
Function GetClientUserName ()
{
Return document. getElementById ("<% = ClientUserName. ClientID %>"). value;
}

Function CheckUserName ()
{
CallbackScriptMethod ();
}

Function OnCallbackCompleted (CallbackResult, context)
{
Document. getElementById ("message"). innerText = CallbackResult;
}

Function OnServerError (error)
{
Alert ("error message" + error );
}
</Script>

GetClientUserNameThis is a function used by the server code to obtain the user name. Use document. getElementById ("<% = ClientUserName. ClientID %>"). value; to obtain the value of Textbox ClientUserName. Note that the ID here is ClientUserName. ClientID instead of ClientUserName. The reason is that the server Control ID may be different from the ID sent from the server to the client. ClientID is the ID sent to the client.

OnCallbackCompletedIs a function that receives processing results from the server.

OnServerErrorIs a function used to handle server errors.

CheckUserNameIs the function called when you click the check button. This function will call the CallbackScriptMethod () function generated by the server to trigger the callback.

The complete page code is as follows:

<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "Default. aspx. cs" Inherits = "_ Default" %>

<! DOCTYPE html PUBLIC "-// W3C // dtd xhtml 1.0 Transitional // EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<Html xmlns = "http://www.w3.org/1999/xhtml">
<Head runat = "server">
<Title> CallbackTest </title>
<Script language = "javascript" type = "text/javascript">
Function GetClientUserName ()
{
Return document. getElementById ("<% = ClientUserName. ClientID %>"). value;
}

Function CheckUserName ()
{
CallbackScriptMethod ();
}

Function OnCallbackCompleted (CallbackResult, context)
{
Document. getElementById ("message"). innerText = CallbackResult;
}

Function OnServerError (error)
{
Alert ("error message" + error );
}
</Script>
</Head>
<Body>
<Form id = "form1" runat = "server">
<Div>
<Asp: TextBox ID = "ClientUserName" runat = "server"> </asp: TextBox>
<Input id = "CheckBtn" type = "button" value = "check account" onclick = "CheckUserName ();"/>
<Span id = "message" style = "color: Red;"> </span>
</Div>
</Form>
</Body>
</Html>

This example is complete. We can look at the effect in IE. (Note: Do not Debug the page in Debug mode when debugging client error handling, because if an exception is thrown in Debug mode, VS will automatically switch to the Code to check the code. Right-click the page and select "view in Browser .)

We can see that when we enter the "pig", in addition to the error information we previously defined, there is also a character in the back. What exactly does this character mean, I think it should be some wrong additional information. I don't know if this is true or not. Please let me know. Thank you.

 

Summary

I feel that. Net brings us a lot of convenience. We only need to write a small amount of code to implement this callback function. However, while enjoying the convenience brought by. Net, we should never forget that this convenience is based on the premise of the loss performance. I personally think that, in the web programming process, if not all elements that need to be accessed in the background, try to use HTML controls, and use fewer server controls. Because the server control is encapsulated, each control has its own lifecycle. It needs to be initialized, loaded, Render, and so on before being output as the elements we see on the client, this must consume server performance.
The path to the program is still being learned. If you have any mistakes, please correct me. Thank you.

 

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.