Ajax. Net user Development Guide

Source: Internet
Author: User
Document directory
  • Sessionstate

Ajax relies on servers as intermediaries to distribute and process requests. To do this, the. NET encapsulation class depends on the client's request object.

  Overview

Ajax relies on servers as intermediaries to distribute and process requests. To do this, the. NET encapsulation class depends on the client's request object, and the XMLHTTPRequest object is supported by most browsers. Therefore, using this object is a good solution. Because the purpose of encapsulation is to hide the implementation of XMLHttpRequest, we will not discuss its implementation details.

The encapsulation class is passed in. net method. Once it is marked, Ajax creates the JavaScript function of the client (similar to the JavaScript function written by the client) and uses XMLHttpRequest to create a server proxy, this proxy maps client functions to server processing functions.

Complicated? No. Let's take a look at the simple example below to show the. NET function.

'Vb. net

Public Function add (firstnumber as integer, secondnumber as integer) as integer

Return firstnumber + secondnumber

End sub

// C #

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

Ajax.net will automatically create a JavaScript function with two parameters named "add". When the client calls this JavaScript function, the request is sent from the backend to the server and the calculation result is returned to the client.

  Initial installation

First, we start by installing ". dll" to your project. If you know how to use it, Skip this section.

If you do not have Ajax. dll, You can first download the latest version of Ajax. Decompress the file and place it in a place that can be referenced by your project. In the. NET project, add a reference to it, and then you can start development using Ajax. dll encapsulation.

If you have trouble installing references, refer to the instructions on this link:

Http://msdn.microsoft.com/library/default.asp? Url =/library/en-US/vbcon/html/vbtskaddingremovingreferences. asp

  SetHttphandle

To make it work, the first step must be done on the web. install httphandle in config to set the encapsulation package. Instead of explaining in detail how httphandle works, we only need to know that they can be used to process Asp.net requests. For example, all requests for *. aspx can be sent to the control handle through the system. Web. UI. pagehandlerfactory class.Ajax/*. ashxRequest sentRequest Processing handle of Ajax. pagehandlerfactory:

<Configuration>
<System. Web>
<Httphandlers>
<Add verb = "post, get" Path = "ajax/*. ashx" type = "Ajax. pagehandlerfactory, Ajax"/>

</Httphandlers>
...
<System. Web>
</Configuration>

The above code tells Asp.net to match any path (Ajax/*. ashx) Requests are sent to the httphandle generated by Ajax. pagehandlerfactory, instead of the default handler factory. You do not need to createAjaxSubdirectory, which is a virtual directory for temporary use only, so other httphandler can use their own directory to use files with the. ashx extension.

  Configuration page

Now we are ready to start coding. Open a new webpage or an existing page, and add the following code to the page_load event in its codebehind file:

'Vb. net

Public class index
Inherits system. Web. UI. Page

Private sub page_load (sender as object, e as eventargs) handles mybase. Load

Ajax. Utility. registertypeforajax (GetType (INDEX ))
'...
End sub
'...
End Class

// C #

Public class index: system. Web. UI. Page {
Private void page_load (Object sender, eventargs e ){
Ajax. Utility. registertypeforajax (typeof (INDEX ));
//...
}
//...
}

Call the registertypeforajax method to generate the following JavaScript code on the page (you can also manually add the following JavaScript code on the page)

<Script language = "JavaScript" src = "ajax/common. ashx"> </SCRIPT>
<Script language = "JavaScript"
Src = "ajax/Namespace. pageclass,Assemblyname. Ashx "> </SCRIPT>

The bold part of the above CodeNamespace. pageclass,AssemblynameMeaning:

Namespace. pageclass Namespace and class of the current page
Assemblyname Name of the Assembly on the current page

The following is the sample. aspx sample output in the ajaxplay project:

<% @ 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">
...
</Form>
</Body>
</Html>

You can test that you can manually open the SRC path (by viewing the source file and copying it) in a browser, and everything works normally. If the output of meaningless text indicates that it is correct so far, and if the output of Asp.net is incorrect, it indicates that there is an error in the middle.

Even if you do not know how httphandle works, you should be able to understand the above description. Through web. config, we can ensure thatAjax/*. ashxThe request is handled by our custom handle. Obviously, the two SCRIPT tags are processed by the custom handle.

  Write Server Functions

Now we write server-side functions, which can be called asynchronously by the client. Although not all return types are supported now, we still insist on adding the server function. In the page class of the codebehind file, add the following method:

'Vb. net

<Ajax. ajaxmethod ()> _

Public Function serversideadd (byval firstnumber as integer, byval secondnumber
As integer) as integer
Return firstnumber + secondnumber
End Function

// C #

[Ajax. ajaxmethod ()]

Public int serversideadd (INT firstnumber, int secondnumber)
{
Return firstnumber + secondnumber;
}

Note that this function has the Ajax. ajaxmethod () custom attribute. The property service informs the Ajax encapsulation class to create a javascript proxy for this method so that it can be called by the client.

  Custom client call

Next, call the function using JavaScript on the client. The Ajax encapsulation class creates a JavaScript function with two parameters named "class name. serversideadd. As the most basic function, all we need to do is call this method and pass the parameters:

<% @ 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 can't just use this powerful feature to remind viewers through alert. That's why all client proxies (such as the class name. serversideadd function) have an additional custom attribute at the same time. This property is a callback function used to process server responses:

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 we have added an additional parameter serversideadd_callback for the serversideadd function, which is the client function used to process server-side responses. This callback function accepts a response object with four key attributes:

Value Return Value of server-side function execution (may be a string, custom object, or dataset)
Error If an error occurs, an error message is returned.
Request Original XMLHttpRequest request
Context A context object

First, we should check whether an error occurs. You can implement this error attribute by throwing an exception in the server-side function. In the above example, a simple alert value is the value attribute. The request attribute can be used to obtain additional information (see the following table)

For more information about XMLHttpRequest, see the following link: http://www.quirksmode.org/blog/archives/2005/02/xmlhttp_linkdum.html.

  Processing type

Returns a complex type.

Ajax supports many types except the int value returned by the serversideadd function. It can directly support integers, strings, double, booleans, datetime, datasets, and Ables, as well as simple custom types and arrays. Other types return strings in tostring mode.

Returning dataset is like a real. Net dataset. Provides a server-side function that returns dataset. We can display it on the client using the following method:

<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 also supports custom classes, but this class can be serialized. 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 ");
}
}

We need to register the getuser agent with the server by calling registertypeforajax:

Private void page_load (Object sender, eventargs e ){
Utility. registertypeforajax (typeof (User ));
}

On the client side, we can call the getuser function in this way:

<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 returned value has three attributes (firstname, lastname, and userid) Like the server object ).

Note: Other types can only be customized by the developer to convert them to the types supported by Ajax when the server-side functions return values. The tostring method is recommended for Ajax.

  Other work methods

  Register functions in other classes

In the above example and description, we complete function registration in the codebehind file on the page, but it does not mean that the registration can only be completed in the codebehide file on the page, you can also register functions in other classes. Recall that the Ajax encapsulation class is used to find those with Ajax in a specific class. the method of the ajaxmethod () attribute to complete the work. These classes use two script fragments on the client to complete the return value description. Using ajax. Utility. registertypeforajax, We can get details of any class we want. For example, the following example shows that it is legal to use server-side functions in other 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

However, we need to first register this proxy class on the calling page. The class name is no longer a page class, but the class we use:

'Vb. net

Private sub page_load (sender as object, e as eventargs) handles mybase. Load
Ajax. Utility. registertypeforajax (GetType (ajaxfunctions ))
'...
End sub

// C #

Private void page_load (Object sender, eventargs e ){
Ajax. Utility. registertypeforajax (typeof (ajaxfunctions ));
//...
}

Remember, the name <classname>. <serversidefunctionname> in this format is called by the client. Therefore, if the above serversideadd function is located in the ajaxfunctions class, instead of the page class, the client call is changed to: ajaxfunctions. serversideadd)

  How does proxy work?

The Second Script tag, as shown in the following example.

<SCRIPT type = "text/JavaScript" src = "/cqyd/ajax/cqyd. schemesendwatch, cqyd. ashx"> </SCRIPT>

Ajax utility is automatically generated through namespaces, classes, and page assembly (you can also manually add them). From this point, we can think of Ajax. pagehandlerfactory obtains the details of a function with custom attributes through reflection. Obviously, Handler looks for functions with the custom attributes of ajaxmethod, obtains their features (return type, name, parameter), and creates a client proxy based on the information. Specifically, Ajax creates a JavaScript Object of the same type as the proxy.

  ReturnUnicodeCharacter

Ajax.net can return Unicode characters from the server to the client. To do this, the returned value must be HTML encoded:

[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;
}

Sessionstate

In the server-side function, you may need to accept the transmitted session information. To do this, you must pass a parameter on the Ajax. ajaxmethod attribute of the server-side function to implement this method.

When viewing That Ajax supports session, Let's first look at other features. In the following example, we have a document management system. When a user edits a document, the document will be locked. Other users can modify the document only when the document is available. If you do not use Ajax, you need to wait for Refresh because you have to constantly check whether the document status is available. This is certainly not a good solution. It is easier to use the Ajax session state support.

First, we write a function. This function traverses the Document ID to find the document you need, store it in the session, and return the document that is not in use:

'Vb. net

<Ajax. ajaxmethod (Httpsessionstaterequirement. Read)> _
Public Function documentreleased () as arraylist
If httpcontext. Current. Session ("documentswaiting") is nothing then
Return nothing
End if
Dim readydocuments as new arraylist
Dim documents () as integer = ctype (httpcontext. Current. Session ("documentswaiting"), INTEGER ())
For I as integer = 0 to documents ENTs. Length-1
Dim document as document = Document. getdocumentbyid (documents (I ))
If not document is nothing andalso document. Status = documentstatus. Ready then
Readydocuments. Add (document)
End if
Next
Return readydocuments
End Function

// C #
[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;
}
}

Httpsessionstaterequirement. Read (or write and readwrite) is specified in the attribute parameter)

The following is the result of writing a JavaScript function to use 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); ">

After the page is loaded, the request is sent to the server function every 10 seconds. If yes, the call back function checks response and displays the latest results.

  Conclusion

Ajax technology can provide a rich client experience, while ajax.net provides the possibility for you to easily implement such powerful functions.

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.