How to Use ajax. dll and ajaxpro. dll

Source: Internet
Author: User

1. first put Ajax. dll to add reference to the project, right-click on the project, there is a [add reference] on the menu, and then step by step that. after adding the DLL file, you will see the Ajax in the reference of the project. dll is successfully added.
2. modify Web. config. Add the following code to the <system. web> element. The Ajax. dll and Ajaxpro. dll reference methods here are different. Be sure to pay attention to them.
<Configuration>
<System. web>
<HttpHandlers>
<! -- The configuration file of Ajax. dll is written as, which is the one I downloaded -->
<Add verb = "POST, GET" path = "ajax/*. ashx" type = "Ajax. PageHandlerFactory, Ajax"/>
<! -- The configuration file of AjaxPro. dll is written as: select different configuration statements based on the DLL file you downloaded -->
<Add verb = "*" path = "ajaxpro/*. ashx" type = "AjaxPro. AjaxHandlerFactory, AjaxPro"/>
</HttpHandlers>
</System. web>
</Configuration>

3. register the page Page_Load event used by AjaxPro during runtime. For example:
Protected void Page_Load (object sender, EventArgs e)
{
Ajax. Utility. RegisterTypeForAjax (typeof (_ Default); // Ajax. dll
AjaxPro. Utility. RegisterTypeForAjax (typeof (_ Default); // Ajaxpro. dll
}
// This _ Default refers to the Class Name of the page class, which is the name of the page. If it is placed in a namespace, you must enter the complete namespace (for example, namespaces. _ Default)

4. Create a server
[Ajax. AjaxMethod] // This sentence must exist. If you are Ajaxpro. dll, write it as [AjaxPro. AjaxMethod].
Public string getValue (int a, int B)
{
// This method transfers two numbers from the client and returns them to the client after adding them to the server. You can write a class in the background of the original page.
Return Convert. ToString (a + B); // The value returned here is the value obtained at the front end. The parameter is already included in the CS file. You can perform the operation as needed, including reading the database.
}
5. Client call.
<% @ Page language = "c #" Codebehind = "WebPage1.aspx. cs" AutoEventWireup = "false" Inherits = "Web. WebPage1" %>
<Script language = "javascript">
Function getValue ()
{

// If it is AjaxPro. dll, add Web. _ Default. getValue. If it is Ajax. dll, you do not need to add the following namespace:
_ Default. getValue (, getGroups_callback); // call the _ Default. getValue method on the server.
// _ Default is the class that writes getValue. If it is written in CS on this page, WebPage1.getValue, 1 and 2 are parameters.
// GetGroups_callback specifies a callback function to receive the client result after the server completes processing.
}

// The user accepts and processes the results returned by the server.
Function getGroups_callback (response)
{
Var dt = response. value; // The value is the value that is finally passed back. Use it whenever you want. Return to the front-end anyway.
Document. getElementById ("Div_1"). innerHTML = dt;
}
</Script>
<Body>
<Div id = "Div_1"> </div>
<Button onclick = getValue ()> Start </botton>
</Body>

Now let's analyze what is executed by clicking the start button. First, execute the getValue () function on the foreground, and the _ Default function in the getValue function. getValue (, getGroups_callback); will execute the CS function in the background. I think this is the essence of AJAX, because the execution here is based on the Ajax component without refreshing the execution of the CS function in the background, generally, we need to call the CS function in the background to refresh the page through the normal method and execute the CS function bound in the background. Here we use Ajax to execute the getValue function in the background without refreshing, 1 and 2 are parameters, which need to be calculated in getValue. The getGroups_callback parameter must be included. Otherwise, what kind of reception do you use to transmit things back in CS, after the getValue function calculates the result in the background, the calculation is already in the background. If you want to calculate the result, it's okay to read the database and then return the value through return, this value can be anything, even if it is an HTML code like "<table> <tr> <td> HelloWorld </td> </tr> </table>, the front-end uses the getGroups_callback () JS function to receive this value, and then the front-end calls it. If you want to use it, you can use it as needed. This is a process of running AJAX, from the front-end to the back-end, and then back to the front-end after computation. How do you understand?

 

Of course, we do not want to use this powerful capability to warn users. This is why all client proxies (such as the JavaScript Sample. ServerSideAd function) accept other features. This feature is the callback function called to handle the response:
Sample. ServerSideAdd (100,99, ServerSideAdd_CallBack );

Function ServerSideAdd_CallBack (response ){
If (response. error! = Null ){
Alert (response. error );
Return;
}
Alert (response. value );
}

 

From the code above, we can see that another parameter is specified. ServerSideAdd_CallBack (see the preceding Code) is a client function used to process server responses. This callback function receives a response object that exposes three main properties.
Value -- the Value actually returned by the server-side function (whether it is a string, a custom object, or a dataset ).
Error -- Error message, if any.
Request -- xml: the original response of the http Request.
Context -- Context object.
First, check the error to see if an error has occurred. By throwing an exception in a server-side function, you can easily handle the error feature. In this simplified example, use this value to warn the user. The Request feature can be used for more information (see the next section ).
Processing type
Return complex types
The Ajax Wrapper can not only process integers returned by the ServerSideAdd function. It also supports integers, strings, double, booleans, DateTime, DataSets, DataTables, custom classes, arrays, and other basic types. All other types return their ToString values.
The returned DataSets is similar to the real. NET DataSet. Suppose a server-side function returns DataSet. We can use the following code to display the content on the client:

<Script language = "JavaScript">
// Asynchronous call to the mythical "GetDataSet" server-side function
Function getDataSet (){
AjaxFunctions. GetDataSet (GetDataSet_callback );
}
Function GetDataSet_callback (response ){
Var ds = response. value;
If (ds! = Null & typeof (ds) = "object" & ds. Tables! = Null ){
Var s = new Array ();
S [s. length] = "<table border = 1> ";
For (var I = 0; I <ds. Tables [0]. Rows. length; I ++ ){
S [s. length] = "<tr> ";
S [s. length] = "<td>" + ds. Tables [0]. Rows [I]. FirstName + "</td> ";
S [s. length] = "<td>" + ds. Tables [0]. Rows [I]. Birthday + "</td> ";
S [s. length] = "</tr> ";
}
S [s. length] = "</table> ";
TableDisplay. innerHTML = s. join ("");
}
Else {
Alert ("Error. [3001]" + response. request. responseText );
}
}
</Script>

Ajax can also return custom classes. The only requirement is that the Serializable attribute must be used. Suppose there are the following classes:
[Serializable ()]
Public class User {
Private int _ userId;
Private string _ firstName;
Private string _ lastName;

Public int userId {
Get {return _ userId ;}
}
Public string FirstName {
Get {return _ firstName ;}
}
Public string LastName {
Get {return _ lastName ;}
}
Public User (int _ userId, string _ firstName, string _ lastName ){
This. _ userId = _ userId;
This. _ firstName = _ firstName;
This. _ lastName = _ lastName;
}
Public User (){}
[AjaxMethod ()]
Public static User GetUser (int userId ){
// Replace this with a DB hit or something
Return new User (userId, "Michael", "Schwarz ");
}
}

You can register the GetUser agent by calling RegisterTypeForAjax:
Private void Page_Load (object sender, EventArgs e ){
Utility. RegisterTypeForAjax (typeof (User ));
}

In this way, you can call GetUser asynchronously on the client:

<Script language = "javascript">
Function getUser (userId ){
User. GetUser (GetUser_callback );
}
Function GetUser_callback (response ){
If (response! = Null & response. value! = Null ){
Var user = response. value;
If (typeof (user) = "object "){
Alert (user. FirstName + "" + user. LastName );
}
}
}
GetUser (1 );
</Script>

 

The value returned in the response is actually an object that exposes the same attributes (FirstName, LastName, and UserId) as the server object ).
Custom Converter
We have seen that the Ajax. NET package can process many different. NET types. However, except for a large number of. NET classes and built-in types, the wrapper only calls ToString () for other types that cannot be correctly returned (). To avoid this, the Ajax. NET package allows developers to create an object converter for smoothly passing complex objects between the server and the client.
Other items
Register functions in other classes
In the above example, our server-side functions are all placed in the code behind the execution page. However, there is no reason not to place these functions in a separate class file. Remember, the way the wrapper works is to find all methods with Ajax. AjaxMethod in the specified class. The required class is specified through the Second Script tag. With Ajax. Utility. RegisterTypeForAjax, we can specify any classes required. For example, it is reasonable to use our server-side functions as separate classes:

Public Class AjaxFunctions
<Ajax. AjaxMethod ()> _
Public Function Validate (username As String, password As String) As Boolean
''Do something
''Return something
End Function
End Class

By specifying the type of the class rather than the page, you can let the Ajax package create a proxy:
Private void Page_Load (object sender, EventArgs e ){
Ajax. Utility. RegisterTypeForAjax (typeof (AjaxFunctions ));
//
}

Remember that the name of the client proxy is <ClassName>. <ServerSideFunctionName>. Therefore, if the ServerSideAdd function is placed in the fictitious AjaxFunctions class above, the client call should be: AjaxFunctions. ServerSideAdd (1, 2 ).

Returns Unicode characters.
The Ajax. NET package can return Unicode characters from the server to the client. Therefore, data must be html encoded on the server before being returned. For example:
[Ajax. AjaxMethod]
Public string Test1 (string name, string email, string comment ){
String html = "";
Html + = "Hello" + name + "<br> ";
Html + = "Thank you for your comment <B> ";
Html + = System. Web. HttpUtility. HtmlEncode (comment );
Html + = "</B> .";
Return html;
}

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.