Ajax| Development Guide
Overview
Ajax relies on the server as an intermediary to distribute and process requests. To do this, the. NET encapsulation class relies on the client's request object, and the XMLHttpRequest object is supported by most browsers, so using this object is a good solution. Because the purpose of encapsulation is to hide the implementation of XMLHttpRequest, we do not discuss his implementation details.
Encapsulation classes are implemented by adding AJAX attribute tags to. NET methods, once tagged, Ajax creates the client's JavaScript function (which is similar to the JavaScript function written by the client) and uses XMLHttpRequest to create a server proxy that maps the client's functions to The processing function of the server.
Is it complicated? No, let's take a look at the following simple example, given 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 immediately automatically creates a JavaScript function with two parameters, name add, and when the client invokes the JavaScript function, the request will be sent from the background to the server side and returned to the client from the result of the calculation.
Initial installation
We start with how to install ". dll" to your project, and of course, if you know how to use it, this section can be skipped.
If you don't have Ajax.dll, you can download the latest version of Ajax first. Unzip the file into a place that can be referenced by your project, add a reference to it in a. NET project, and then start using the Ajax.dll package for development.
|
If you are having trouble installing a reference, refer to the link's description:
Http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbcon/html/vbtskaddingremovingreferences.asp
|
Set up
Httphandle
In order for it to work, the first step must be to install the Httphandle package in Web.config, not to explain in detail how httphandle works, we just need to understand that they can be used to process asp.net requests. For example, all requests for *.aspx can be sent through the System.Web.UI.PageHandlerFactory class to the control handle, simply to say that we put any
ajax/*.ashx
the request sent toAjax.pagehandlerfactory Request Processing handle:
The code above tells ASP.net to match anything to a particular path (
ajax/*.ashxThe request is sent to the httphandle generated by the ajax.pagehandlerfactory and is no longer the default handler factory. You don't need to create
Ajaxsubdirectory, which is a virtual directory used only for temporary use, so other httphandler can use their own directories for a file with the. ashx extension.
Configuration page
Now we're ready to start coding. Open a new Web page or a page that already exists, adding 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)); //... } //... } |
A call to the Registertypeforajax method produces the following JavaScript code on the page (alternatively, you can manually add the following JavaScript code to the page)
The bold part of the code above
NAMESPACE. Pageclass,
AssemblyNameThe meanings are as follows:
NAMESPACE. Pageclass
|
Namespaces and classes for the current page
|
AssemblyName
|
The name of the assembly for the current page
|
The following is a sample output from Sample.aspx in the Ajaxplay project:
<%@ Page inherits= "ajaxplay.sample" codebehind= "Sample.aspx.cs" ...%>
...
|
You can test it by manually opening the SRC path (by viewing the source file and copy) through the browser, and everything works. If the output of the meaningless text represents so far correct, if the output asp.net error, then an error occurred in the middle.
Even if you don't understand how httphandle works, you should be able to understand the above description. Through web.config, we can ensure that sending to
ajax/*.ashxThe request is handled by our custom handle, and it is clear that the two script tags are handled by the custom handle.
writing service-side functions
Now we write server-side functions that can be invoked asynchronously by the client. Although it is not yet possible to support all of the return types, we still adhere to the server-side add functionality. In the page class of the Codebehind file, add the following method:
' VB.net
_
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 a ajax.ajaxmethod () custom attribute, and the property service tells the Ajax wrapper class to create a JavaScript proxy for this method so that it can be invoked by the client.
Custom Client Invocation
The next step is to invoke the function with JavaScript on the client. The Ajax wrapper class creates a JavaScript function with two parameters, and the name is the 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" ...%>
|
Of course, we can't use such a powerful feature just to alert the viewer through alert, which is why all the client proxies, such as class names. Serversideadd function) with an additional custom attribute at the same time. This property is the callback function used to handle the server response:
Sample.serversideadd (100,99, serversideadd_callback);
function Serversideadd_callback (response) { if (response.error!= null) { alert (response.error); Return } alert (Response.value); } |
As you can see from the code above, we added an extra parameter to the Serversideadd function Serversideadd_callback, which is the client function used to handle the server-side response. This callback function accepts a response object with four key attributes:
Value
|
The return value performed by the server-side function (possibly a string, custom object, or dataset)
|
Error
|
If an error occurs, an error message is returned.
|
Request
|
The original XMLHttpRequest request
|
Context
|
A Context Object
|
We should first check for errors, and you can implement this error property by throwing an exception on the server-side function. In this example, we simply alert a value, which is the Value property; The Request property can be used to obtain additional information (see table below)
|
If you want to know more about XMLHttpRequest, you can view the links below: http://www.quirksmode.org/blog/archives/2005/02/xmlhttp_linkdum.html
|
Processing Type
returns a complex type
Ajax can support many types other than the int value returned by the Serversideadd function above us. He can directly support integers, strings, double, Booleans, DateTime, Datasets and DataTables, and also supports simple custom types and arrays. Other types return a string by their ToString method.
Returning to a dataset works like a real. NET DataSet. Gives a server-side function that returns a dataset, which we can display on the client by using the following method:
Ajax can also support custom classes, but this class needs to be serialized. such as the following class:
[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)); } |
At the client we can invoke the GetUser function in this way:
The return value has three properties like a server-side object (FirstName, LastName and UserId).
Translator Note: Other types can only be implemented by developers by customizing the conversion to AJAX-supported types when server-side functions are returned, Ajax recommends the ToString method.
Other ways of working
registering functions in other classes
In the above example and the description, we are through the page in the codebehind file to complete the function registration, but not that only in the page codebehide file to complete the registration, we can also register the function in other classes. Recall that the Ajax encapsulation class completes the work by looking up a method within a particular class that has the Ajax.ajaxmethod () attribute, which completes the return value description at the client and through two script fragments. Using Ajax.Utility.RegisterTypeForAjax, we can get the details of any class we want. For example, the following example shows that we are legitimate to use server-side functions in other classes:
Public Class Ajaxfunctions _ Public Function Validate (username as String, password as String) as Boolean ' Do something ' Return something End Function End Class |
But we need to register this proxy class first on the call page, and the class name is no longer a page class, it's 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 client invokes the name <ClassName>. <ServerSideFunctionName> that uses this format. Therefore, if the Serversideadd function above is in the Ajaxfunctions class, not the page class, the client call becomes: Ajaxfunctions.serversideadd (1,2)
How does an agent work?
The second script tag, as shown in the following example
<script type= "Text/javascript" src= "/cqyd/ajax/cqyd". Schemesendwatch,cqyd.ashx "> </script>
is generated automatically by the Ajax utility through namespaces, classes, and page assemblies (and, of course, manually), from which we can think of the details of the function that the ajax.pagehandlerfactory is using reflection to get a custom attribute. Obviously, handler looks for functions with Ajaxmethod custom properties, obtains their characteristics (return type, name, parameters) and creates a client proxy based on that information. In particular, Ajax creates a JavaScript object with the same type as the proxy.
return
Unicode
character
Ajax.NET can return Unicode characters from the server side to the client, in order to do this, the value returned when the service-side function returns must be HTML-encoded:
[Ajax.ajaxmethod]
public string Test1 (string name, string email, string comment) { String html = ""; html = "Hello" + name + " "; html = "Thank for your comment "; HTML + System.Web.HttpUtility.HtmlEncode (comment); HTML + = "."; return HTML; } |
SessionState
In the service-side function, you may need to accept the delivered session information, in order to do this, you must pass a parameter on the Ajax.ajaxmethod attribute of the service-side function that you want to implement this way.
When looking at Ajax to support the session, let's look at other features first. In the following example, we have a document management system that locks up the document when a user edits it, and other users need to wait until the document is available to be modified. Without Ajax, users need to keep waiting to refresh because they have to constantly check that the status of the document is available, which is certainly not a good solution. This is easier with Ajax session state support.
We first write a function that, by traversing the document ID, finds the document that the user needs, stores it in the session, and returns the document that is not occupied:
' VB.net
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 an Integer = 0 to documents. Length-1 Dim Document as document = document. Getdocumentbyid (Documents (i)) If not the 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; } } |
We indicated the httpsessionstaterequirement.read in the attribute argument (also can be write and ReadWrite)
The following writes the JavaScript function to use this method to bring the result:
Every 10 seconds after the page is loaded, the server function is requested once. If there is a return, the call back function checks the response and displays the latest results.
Conclusions
Ajax technology can provide a rich customer experience for clients, and Ajax.NET provides the possibility for you to achieve such powerful functionality easily.