Implementing Ajax in ASP.net

Source: Internet
Author: User
Tags add object end functions net string version tostring
Ajax|asp.net

The recent upsurge of asynchronous JavaScript and XML (AJAX) is entirely due to Google's use in Google suggest and Google Maps. For ASP.net, Ajax does not require a postback for server-side processing, enabling the client (browser) to have rich server-side capabilities. In other words, it provides a framework for asynchronous assignment and processing requests and server responses. Ajax has taken advantage of some technologies that are not very novel, but the hobby of these technologies (added together as Ajax) has recently suddenly warmed up.

Please try the Ajax of Michael Schwarz. NET wrapper, which ASP.net developers to quickly and easily deploy AJAX-enabled pages. It should be noted that the wrapper is in the early stages of development and therefore not fully mature.


How it works--an overview

Ajax relies on proxy (broker) to assign and process requests for a roundtrip server. On this,. NET wrapper relies on client XMLHttpRequest objects. Most browsers support the XMLHttpRequest object, which is why it is selected. Since the purpose of the wrapper is to hide the XMLHttpRequest implementation, we will not discuss it in detail.

The wrapper itself through will. NET functions are marked as Ajax methods to work. Tag, Ajax creates the corresponding JavaScript functions, which, like any JavaScript function, can be invoked on the client using XMLHttpRequest as proxies. These agents are then mapped back to the server-side functions.

Is it complicated? is not complicated. Let's take a look at an example. Suppose there was one. NET function:


ublic int Add (int firstnumber, int secondnumber)
{
return firstnumber + secondnumber;
}


Ajax. NET wrapper will automatically create a JavaScript function named "Add" with two parameters. When the function is called using JavaScript (on the client), the request is passed to the server and the result is returned to the client.

Initial settings

Let's begin by introducing the steps for the. dll used in the Setup project. If you know how to add a. dll file reference, you can skip this section.

First, if not, download the latest AJAX version. Unzip the downloaded file and place the Ajax.dll in the project's referencing folder. In Visual Studio.NET, organic Solution Explorer's References (Reference) node and select Add Reference (Add Reference). In the Open dialog box, click Browse and locate the Ref/ajax.dll file. Click Open and OK (confirm). So you can use Ajax. NET wrapper has been programmed.

Establish HttpHandler

In order to ensure normal work, the first step is to set the HttpHandler of the wrapper in the web.config. There is no need to explain in detail what httphandlers is and how it works, as long as it is known that they are used to process asp.net requests. For example, all *.aspx page requests are handled by the System.Web.UI.PageHandlerFactory class. Similarly, we allow all requests for ajax/*.ashx to be handled by Ajax.pagehandlerfactory:

<configuration>
<system.web>
<add verb= "Post,get" path= "Ajax/*.ashx"
Type= "ajax.pagehandlerfactory, Ajax"/>

<system.web>
</configuration>

In short, the above code tells ASP.net that any request that matches the specified path (AJAX/*.ASHX) is handled by the ajax.pagehandlerfactory rather than by the default handler factory. There is no need to create Ajax subdirectories, this mysterious directory is used only to allow other httphandlers to be able to use it in their own subdirectories. ashx extensions.

Create a page

Now we can start coding. Create a new page or open an existing page, and in the file code, 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 raise the following JavaScript on the page (or add two lines of code to the page manually):

<script language= "javascript" src= "Ajax/common.ashx" ></script>
<script language= "JavaScript"
Src= "Ajax/namespace.pageclass,assemblyname.ashx" ></script>


The last line of the meaning is:

namespace.pageclass--the namespace and class of the current page (usually the value of the Inherits attribute in the @page Directive)
assemblyname--the name of the assembly to which the current page belongs (usually the project name)
The following is an example of the results of the Sample.aspx page in the Ajaxplay project:

<%@ Page inherits= "ajaxplay.sample" codebehind= "Sample.aspx.cs"%>
<script language= "javascript" src= "Ajax/common.ashx" ></script>
<script language= "JavaScript"
Src= "Ajax/ajaxplay.sample,ajaxplay.ashx" ></script>
<body>
<form id= "Form1" method= "POST" runat= "Server" >

</form>
</body>


You can manually navigate to the SRC path (view source code, copy and paste path) in the browser to check that everything is OK. If two paths output some (seemingly) meaningless text, it's all right. If there are no outputs or asp.net errors, there are problems in some places.

Even if you don't know how httphandlers works, the example above is easy to understand. Through web.config, we have ensured that all requests for ajax/*.ashx are handled by custom handlers. Obviously, the two script tags here will be handled by a custom handler.

Creating server-side functions

Now, create a server-side function that can be accessed asynchronously from the client invocation. Since all return types are not currently supported (don't worry, the new version will be developed on the current basis), let's continue using 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 a set of Ajax.ajaxmethod properties. This property tells the wrapper that these methods create a JavaScript proxy to invoke on the client.

Client Calls

The final step is to call the function with JavaScript. The Ajax wrapper is responsible for creating a JavaScript function Sample.serversideadd with two parameters. For this simplest function, you only need to call the method and pass two numbers:

<%@ Page inherits= "ajaxplay.sample" codebehind= "Sample.aspx.cs"%>
<script language= "javascript" src= "Ajax/common.ashx" ></script>
<script language= "JavaScript"
Src= "Ajax/ajaxplay.sample,ajaxplay.ashx" ></script>
<body>
<form id= "Form1" method= "POST" runat= "Server" >
<script language= "JavaScript" >
var response = Sample.serversideadd (100,99);
alert (Response.value);
</script>
</form>
</body>

Of course, we do not want to use this powerful ability to warn users only. This is why all client proxies, such as JavaScript sample.serversidead functions, also accept other features. This feature is the callback function invoked 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);
}

We can see from the above code that we have specified another parameter. Serversideadd_callback (see also the above code) is a client function for handling server responses. This callback function receives a response object that exposes three primary properties

value--the value that the server-side function actually returns (whether it is a string, a custom object, or a dataset).
error--error messages, if any.
Request--xml the original response of the HTTP request.
context--the context object.
First we check the error only to see if there is an error. By throwing an exception in a server-side function, you can easily handle the error attribute. In this simplified example, the user is then warned with this value. The request attribute can be used to obtain more information (see the next section).

Processing type

Return Complex Type

The Ajax wrapper can handle not only the integers returned by the Serversideadd function. It also currently supports basic types such as integers, strings, double, Booleans, DateTime, datasets, and DataTables, as well as custom classes and arrays. All other types return their ToString values.

The returned datasets is almost the same as the real. NET DataSet. Assuming a server-side function returns the dataset, we can display the contents of the client in the following code:


<script language= "JavaScript" >
Asynchronous called 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, and the only requirement is that they must be marked with the Serializable attribute. The following classes are assumed:
[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 can register the GetUser agent by calling Registertypeforajax:

private void Page_Load (object sender, EventArgs e) {
Utility.registertypeforajax (typeof (User));
}

This allows GetUser to be invoked asynchronously at 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 properties as the server-side objects (FirstName, LastName, and UserID).

Custom Converters

We've seen that Ajax. NET wrapper can handle many different. NET types. But except for a lot. NET class and built-in type, the wrapper invokes only ToString () on other types that cannot be returned correctly. To avoid this situation, Ajax. NET wrapper allows the developer to create an object converter for smooth delivery of complex objects between the server and the client.

Other matters

Registering functions in other classes

In the example above, our server-side functions are placed in the code behind the execution page. However, there is no reason why these functions should not be placed in a separate class file. Remember that the wrapper works by discovering all the methods with Ajax.ajaxmethod in the specified class. The required classes are specified by a second script tag. Using Ajax.Utility.RegisterTypeForAjax, we can specify any class that is 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

You can have the Ajax wrapper create an agent by specifying the type of the class instead of the page:


private void Page_Load (object sender, EventArgs e) {
Ajax.Utility.RegisterTypeForAjax (typeof (Ajaxfunctions));
//
}

Remember, the name of the client agent is <ClassName>.<ServerSideFunctionName>. Therefore, if the Serversideadd function is placed in the fictitious Ajaxfunctions class above, the client invocation should be: Ajaxfunctions.serversideadd (1,2).

How the agency works in the end

The second script tag generated by the Ajax tool (also inserted manually) passes the page's namespace, class name, and assembly. Based on this information, Ajax.pagehandlerfactory is able to use reflection to get the details of any function that has a particular attribute. Obviously, the handler functions look for functions that have ajaxmethod properties and get their signatures (return type, name, and parameters) from the ability to create the necessary client proxies. Specifically, the wrapper creates a JavaScript object with the same name as the class that provides the proxy. In other words, given a server-side class ajaxfunctions with an Ajax Serversideadd method, we get the Ajaxfunction JavaScript object that exposes the Serversideadd function. This action is seen if you point the browser to the path of the second script label.

return Unicode characters

Ajax. NET wrapper to return Unicode characters from the server to the client machine. To do this, the data must be HTML encoded on the server before it is returned. Like what:


[Ajax.ajaxmethod]
public string Test1 (string name, string email, string comment) {
String html = "";
HTML + + "Hello" + name + "<br>";
HTML + + "Thank for your comment <b>";
HTML + System.Web.HttpUtility.HtmlEncode (comment);
HTML + + "</B>.";
return HTML;
}

SessionState

Session information is likely to be accessed in server-side functions. To do this, you only need to tell Ajax to enable this functionality by passing a parameter to the Ajax.ajaxmethod property.

While examining the ability of the wrapper session, let's look at a few other features. In this example we have a document management system that locks the document when the user edits it. Other users can request notification when the document is available. Without Ajax, we can only wait for the user to return again to check that the requested document is available. is clearly not ideal. Using AJAX, which supports session state, is very simple.

The first is to write a server-side function that iterates through the DocumentID (saved in session) that the user wants to edit and returns all the freed 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 we have specified the Httpsessionstaterequirement.read value (you can also use write and ReadWrite).

Now write 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 documents are ready!<br/>";
for (var i = 0; i < response.value.length; ++i) {
div.innerhtml + = "<a href=\" edit.aspx?documentid= "+ response.value[i". DocumentID + ">" + response.value[i]. Name + "</a><br/>";
}
}
settimeout (' page. documentreleased (Documentsready_callback) ', 10000);
}
</script>
<body >

Conclusion

Ajax technology has spawned a robust and rich web interface that only desktop development has. Ajax. NET wrapper makes it easy for you to take advantage of this new and powerful technology. Please note that Ajax. NET wrappers and documents are still under development.


Posted on 2005-10-29 10:12 Gao Haidong Reading (2070) Comments (4) Edit collection to 365Key categories: asp.net, AJAX

Comments
# Re: Implementing Ajax in ASP.net 2005-11-26 20:39 Yang Li
Feel more confused, can you do the sample to provide download it? Reply


# Re: implementing Ajax 2005-12-05 17:04 in asp.net akinggmx
After adding a DLL reference in Web.config to establish a HttpHandler compile run the access is denied: "Ajax." What's wrong?
Reply


# re:keyi 2006-02-08 13:57 netfuns
I'm over the top, OK.
Upstairs, maybe Webconfig didn't get a good response.


# Re: implementing Ajax 2006-02-08 14:06 in asp.net netfuns
<system.web>
<add verb= "Post,get" path= "Ajax/*.ashx"
Type= "ajax.pagehandlerfactory, Ajax"/>


It's a good match, exactly.

aspx file

<script language= "javascript" src= "ajax/common.ashx" ></script>//this line
Direct Plus no Tube
<script language= "JavaScript"
Src= "Ajax/xxx,xxx.ashx" ></script>//before the XXX is the full class name of the CS file, that is, plus the namespace, the following xxx is the assembly name, is the file name of the DLL after the project. If the project name is WebApplication1, fill in the WebApplication1


CS file on
Using Ajax.jason;
Using Ajax

Page_Load
{
Ajax.Utility.RegisterTypeForAjax (typeof (WebForm1));//webform1 is the name of the class on your page.
}



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.