Ajax development using Ajax. dll

Source: Internet
Author: User
The recent upsurge in Asynchronous JavaScript and XML (Ajax) is entirely due to Google's use of Google suggest and Google Maps. For ASP. NET, AJAX can be processed on the server without returning data, so that the client (browser) has rich server capabilities. In other words, it provides a framework for Asynchronously assigning and processing requests and server responses. Ajax uses some existing technologies that are not very novel, but the hobby of these technologies (together with Ajax) has suddenly heated up.

Please try Michael Schwarz's Ajax. Net Package, through which ASP. NET developers can quickly and conveniently deploy pages that are easy to use Ajax functions. It should be noted that this package is in the initial development stage, so it is not completely mature.

How it works-Overview
Ajax relies on the broker to assign and process requests to and from the server. The. NET package depends on the XMLHTTPRequest object of the client. Most browsers support XMLHttpRequest objects, which is why they are selected. Because the purpose of the package is to hide the implementation of XMLHttpRequest, we will not discuss it in detail.
The wrapper itself works by marking. NET functions as Ajax methods. After marking, Ajax creates the corresponding JavaScript functions. These functions (like any JavaScript function) can be called on the client using XMLHttpRequest as a proxy. These proxies are then mapped back to the server-side functions.
Complicated? Not complex. Let's look at an example. Suppose there is a. net function:

Ublic int add (INT firstnumber, int secondnumber)
{
Return firstnumber + secondnumber;
}

The Ajax. Net Package automatically creates a JavaScript function named "add" with two parameters. When you call this function using JavaScript (on the client), the request is sent to the server and the result is returned to the client.
Initial settings
First, we will introduce the. dll steps used in the "Install" project. Skip this section if you know how to add a. dll file reference.
First, if not, download the latest Ajax version. Decompress the downloaded file and place Ajax. dll in the reference folder of the project. In Visual Studio. NET, select the "references" node of the Organic Solution Explorer and add reference ). In the displayed dialog box, Click Browse and find the ref/ajax. dll file. Click Open and OK ). In this way, you can program with the Ajax. Net package.
Create httphandler
To ensure normal operation, the first step is to set the httphandler of the package in Web. config. You don't need to explain in detail what httphandlers is and how it works, as long as you know that they are used to process ASP. NET requests. For example, all *. ASPX page requests are processed by the system. Web. UI. pagehandlerfactory class. Similarly, we make all ajax/*. ashx requests processed by Ajax. pagehandlerfactory:
<Configuration>
<System. Web>
<Httphandlers>
<Add verb = "post, get" Path = "ajax/*. ashx"
Type = "Ajax. pagehandlerfactory, Ajax"/>
</Httphandlers>

<System. Web>
</Configuration>

In short, the aboveCodeTells ASP. NET that any request that matches the specified path (ajax/*. ashx) is handled by Ajax. pagehandlerfactory rather than by default.ProgramFactory. You do not need to create an Ajax subdirectory. This mysterious directory is used to allow other httphandlers to use the. ashx extension in their own subdirectories.

Create page
Now we can start encoding. Create a new page or open an existing page. In the code after file, add the following code for the page_load event:
Public class index: system. Web. UI. Page {
Private void page_load (Object sender, eventargs e ){
Ajax. Utility. registertypeforajax (typeof (INDEX ));
//
}
//
}

Calling registertypeforajax will trigger the following JavaScript on the page (or manually Add the following two lines of code to the page ):
<Script language = "JavaScript" src = "ajax/common. ashx"> </SCRIPT>
<Script language = "JavaScript"
Src = "ajax/namespace. pageclass, assemblyname. ashx"> </SCRIPT>

the last line indicates:
namespace. pageclass -- The namespace and class of the current page (usually the value of the inherits attribute in the @ page command)
assemblyname -- Name of the Assembly to which the current page belongs (usually the project name)
below is the sample in the ajaxplay project. example of ASPX page result:
<% @ page inherits = "ajaxplay. sample "codebehind =" sample. aspx. CS "%>









You can manually navigate to the SRC path in the browser (ViewSource code, Copy and paste the path) to check whether everything is normal. If both paths output meaningless texts, everything would be fine. If nothing is output or an ASP. NET error occurs, it indicates that there are some problems.
Even if you don't know how httphandlers works, the above example is easy to understand. Through web. config, we have ensured that all ajax/*. ashx requests are processed by custom handlers. Obviously, the two script labels here will be processed by the Custom Handler.
Create Server Functions
Create a server-side function that can be asynchronously accessed from a client call. Because at present, it does not support all the return types (don't worry, we will develop a new version based on the current version). Let's continue to use the simple serversideadd function. In the code after file, add the following code to the page:
[Ajax. ajaxmethod ()]
Public int serversideadd (INT firstnumber, int secondnumber)
{
Return firstnumber + secondnumber;
}

Note that these functions have the Ajax. ajaxmethod attribute set. This property tells the wrapper how to create these methods Javascript Proxy to be called on the client.
Client call
The last step is to use JavaScript to call the function. The Ajax package is responsible for creating the JavaScript function sample. serversideadd with two parameters. For this simplest function, you only need to call this method and pass two numbers:
<% @ Page inherits = "ajaxplay. sample" codebehind = "sample. aspx. cs" %>
<HTML>
<Head>
<Script language = "JavaScript" src = "ajax/common. ashx"> </SCRIPT>
<Script language = "JavaScript"
Src = "ajax/ajaxplay. sample, ajaxplay. ashx"> </SCRIPT>
</Head>
<Body>
<Form ID = "form1" method = "Post" runat = "server">
<Script language = "JavaScript">
VaR response = sample. serversideadd (100,99 );
Alert (response. value );
</SCRIPT>
</Form>
</Body>
</Html>

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:

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 . . Therefore, if the serversideadd function is placed in the fictitious ajaxfunctions class above, the client call should be: ajaxfunctions. serversideadd (1, 2 ).
how the proxy Works
the Second Script tag (which can be inserted manually) generated by the Ajax Tool transfers the page namespace, class name, and assembly. Based on this information, Ajax. pagehandlerfactory can use reflection to obtain detailed information about any function with specific attributes. Obviously, the processing function searches for functions with the ajaxmethod attribute and obtains their signatures (return types, names, and parameters), from the ability to create necessary client proxies. Specifically, the Package creates a JavaScript Object with the same name as the class, which provides a proxy. In other words, given a server-side class ajaxfunctions with Ajax serversideadd method, we will get the ajaxfunction JavaScript Object that exposes the serversideadd function. If you direct the browser to the path of the Second Script tag, you will see this action.
Unicode Character returned
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 + "
";
HTML + = "Thank you for your comment ";
HTML + = system. web. httputility. htmlencode (comment);
HTML + = "
. ";
return HTML;
}

Sessionstate
The server functions may need to access session information. Therefore, you only need to tell ajax to enable this function by passing a parameter to the Ajax. ajaxmethod attribute.
While examining the package's session capabilities, let's take a look at several other features. In this example, we have a document management system that locks documents when users edit them. Other users can request a notification when the document is available. Without Ajax, we can only wait for the user to return again to check whether the requested document is available. Obviously not ideal. It is very easy to use Ajax that supports session status.
First, write the server-side function. The objective is to traverse the entid that you want to edit (stored in the session) and return all released documents.
[Ajax. ajaxmethod (httpsessionstaterequirement. Read)]
Public arraylist documentreleased (){
If (httpcontext. Current. session ["documentswaiting"] = NULL ){
Return NULL;
}
Arraylist readydocuments = new arraylist ();
Int [] documents = (INT []) httpcontext. Current. session ["documentswaiting"];
For (INT I = 0; I <documents. length; ++ I ){
Document document = Document. getdocumentbyid (documents [I]);
If (document! = NULL & document. Status = documentstatus. Ready ){
Readydocuments. Add (document );
}
}
Return readydocuments;
}
}

Note that the value httpsessionstaterequirement. Read is specified (write and readwrite can also be used ).
Now write the Javascript that uses this method:
<Script language = "JavaScript">
Function documentsready_callback (response ){
If (response. Error! = NULL ){
Alert (response. Error );
Return;
}
If (response. value! = NULL & response. value. length> 0 ){
VaR DIV = Document. getelementbyid ("status ");
Div. innerhtml = "The following statements are ready! <Br/> ";
For (VAR I = 0; I <response. value. length; ++ I ){
Div. innerhtml + = "<a href = \" Edit. aspx? Entid = "+ response. value [I]. entid +" \ ">" + response. value [I]. Name + "</a> <br/> ";
}
}
SetTimeout (''page. documentreleased (documentsready_callback) '', 10000 );
}
</SCRIPT>
<Body onload = "setTimeout (''document. documentreleased (documentsready_callback)'', 10000); ">

Conclusion
Ajax technology has given birth to a robust and rich web interface that was originally available only for desktop development. The Ajax. Net package allows you to easily use this new powerful technology. Please note that the Ajax. Net Package and documentation are still under development

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.