Implement Ajax-style Web development with ASP. NET 2.0

Source: Internet
Author: User
Abstract Developing highly interactive web applications based on AJAX technology in the past few months Program The design pattern quickly becomes popular. Currently, highly configurable web applications, such as Google Maps and A9, are using these technologies to create a rich client user experience. In fact, using Ajax technology for web development is not the result of recent research, but these technologies have been continuously updated and improved.

This article has three purposes. First, I want to provide an advanced overview of an Ajax-style application. Secondly, I want to describe the asynchronous callback mechanism of ASP. NET 2.0 in detail. Finally, I would like to look forward to the future improvement of tools and frameworks for building Ajax-style applications.

In summary, Ajax-style Web applications show the following features:

· Asynchronous requests to the Web server-when the user waits for a response from the Web server, the browser user interface is not blocked, but can continue to respond to user interaction.

· Highly dependent on browser-based logic written in Javascript-the latest W3C Dom improvements and standardization provide support for dynamic client UI updates.

· XML-based data exchange between browsers and web servers-XMLHTTP Objects make it possible to communicate with Web servers without the need to reload pages.

The biggest difference between an Ajax application and a traditional web application is that each user interaction does not send every HTTP request to the Web server. Instead, the browser-based logic implemented by JavaScript controls the control, and then the control determines whether to process requests locally or make asynchronous calls to the server. Once the asynchronous call to the server ends, the client logic immediately Updates relevant parts of the UI. This method has the following advantages:

· Richer user experience. For example, when a Google Map user is dragging a map in one direction, the system sends an asynchronous request to the server in the background, and the result is that the user can continue to drag the map after the screen boundary is exceeded. In this way, new images are available when you move the map further. This leads to a faster response.

· Since the call status to the server over XMLHTTP is not lost, Ajax applications can avoid re-generating the UI every time.

· More logic is on the browser side, which reduces the number of back-and-forth requests to the Web server and comprehensively improves the potential of the system.

Despite so many advantages, Ajax-style applications still have some shortcomings. For example, it is difficult to develop Ajax-style applications because of the lack of corresponding frameworks (a set of UI classes similar to Windows MFC toolkit) and IDE (debugging, visual design, and so on) yes. In addition, Ajax-based development requires a person to have at least two languages (DHTML and JavaScript ). In addition, it takes longer to encode an Ajax-style application because it requires additional tests to support multi-browser versions and types. Finally, as the JavaScript-based source code is accessible to end users, security analysis becomes very important during development.

Fortunately, the emergence of tools such as Atlas, Ajax. net, and Google Maps APIs provides better support for building Ajax-style applications in the future. Next, we will discuss the development history of supporting technologies for building Ajax-style applications and what we expect from the latest toolkit atlas.

Let's first discuss XMLHTTP objects. This object was initially introduced by Microsoft and will be implemented on other platforms (including Mozilla and Apple's Safari browser) in the future. XMLHTTP supports asynchronous requests to the Web server, which allows the client to call the Web Server Based on JavaScript logic without the need to reload the entire page.

In other words, it is entirely possible to interact with the web server in the background without causing the whole page to be reloaded.

XMLHTTP objects are directly used. For simplicity, let's only consider the specific ie syntax. In fact, the implementation Syntax of XMLHTTP in other browsers is similar to that discussed here.

Request = new activexobject ("Microsoft. XMLHTTP ");
If (request) {request. onreadystatechange = callbackhandler;
Request. Open ("get", URL, true );
Request. Send ();
}
Function callbackhandler (){
If (request. readystate = 4) & (request. Status = 200 ){
String response = request. responsexml;
// Update the UI
}
}

AboveCodeThe first step is to instantiate the Microsoft. XMLHTTP class. Step 2: Set the attributes of the XMLHTTP instance we just created, including the address of the callback function that will be controlled when the XMLHTTP request is complete. Because we are making asynchronous calls to the server (implemented by setting the third parameter of the Open Method to true), we need the address of the callback function. During the implementation of the callback function, we perform additional checks to ensure that the request is complete.

As you can see from the sample code aboveCubeXMLHTTP object is quite simple. However, it is difficult to integrate XMLHTTP into other parts of the httppage lifecycle-for example, how to ensure that method calls on the server can access the status of other controls on the page? To correctly initialize the status of these controls, the server-side callback process requires an httppage lifecycle similar to the callback process. Another challenge for using XMLHTTP objects directly is that as developers, we need to consider different browser types. Fortunately, ASP. NET 2.0 provides a reusable mode that makes access callback very easy. Note that several controls, including the gridview and Treeview, are released along with ASP. NET 2.0, all using the callback mechanism.

Let's take a look at the server implementation principles. First, define a new interface icallbackeventhandler on the server side. This icallbackeventhandler interface is required for any ASPX page (or controls that intend to support client callback. The icallbackeventhandler interface defines a method called raisecallbackevent. This method uses a string type parameter and returns a string.

On the client side, a special JavaScript function needs to be called to initialize the callback function. You can call clientscriptmanager. getcallbackeventreference to obtain a reference to this special JavaScript function. The call to getcallbackeventreference generates a callback reference. When calling this callback function, you only need to pass a string type parameter. This is consistent with the raisecallbackevent signature on the server. This is what you need to do to establish a callback mechanism on the client. The implementation of the raisecallbackevent method that hooks the client callback function to the icallbackeventhandler interface on the server is completed by the framework. The special JavaScript Functions of the initialization callback mechanism mentioned above use the other two parameters (_ callbackparam and _ callbackid) as feedback data, they represent the string parameters passed to the caller and the Control ID. On the server side, ASP. NET detects the existence of the other two parameters and routes requests to the appropriate controls. This will cause the raisecallbackevent method on the target control to be called. To solve the initialization problem of the control on the page mentioned above, ASP. NET provides a simplified version of httppage lifecycle during a service callback at runtime. This cycle includes a specific stage of page initialization, observation status loading, page loading, and callback function event processing. Once the callback function event is processed by the control, other stages of the httppage lifecycle will be skipped.

To help you better understand the callback mechanism of ASP. NET 2.0, the release package contains a simple progress bar control, which relies on callback to determine the status of a task determined by the server. The following list 1 shows the code of the progressbar control. To support the client callback function, this control implements the icallbackeventhandler interface. For demonstration purpose, the raisecallbackevent method simply finds a counter stored in the session, adds 1 to the counter each time, and returns the new value to the client. Finally, list 2 shows the JavaScript code that initializes the callback function. It uses this. Page. clientscript. getcallbackeventreference to obtain a secure reference to the function that requires initialization callback.

List 1: progressbar. CS

Public class progressbar: system. Web. UI. Control, system. Web. UI. icallbackeventhandler {
Private int percentcompleted {
Get
{
If system. Web. httpcontext. Current. session ["percentcomplete"] = NULL ){
System. Web. httpcontext. Current. session ["percentcomplete"] = 1;
}
Else {
System. Web. httpcontext. Current. session ["percentcomplete"] = (INT) system. Web. httpcontext. Current. session ["percentcomplete"] + 1;
}
Return (INT) system. Web. httpcontext. Current. session ["percentcomplete"];
}
Set
{
System. Web. httpcontext. Current. session ["percentcomplete"] = 1;
}
}
Public String raisecallbackevent (string eventarguments ){
Int percent = This. percentcompleted;
If (percent & gt; 100)
{
This. percentcompleted = 1;
Return "completed ";
}
Else
{
Return percent. tostring () + "% ";
}
}
Protected override void onprerender (eventargs e ){
This. Page. clientscript. registerclientscriptblock (typeof (progressbar ),
"Progressbar", this. getclientsidescript (), true );
Base. onprerender (E );
}
Protected override void render (htmltextwriter writer ){
System. Text. stringbuilder sb = new stringbuilder ();
SB. append (@ "<Table id =" "progressbarcontainer" "bgcolor =" "lightsteelblue ""
Border = "" 0 "" width = "400" "style =" "display: none; position: absolute;
Z-INDEX: 10 ""> ");
SB. append (@ "<tr> <TD colspan =" "3" "style =" "padding: 3px 2px 2px 10px" "> ");
SB. append (@ "<font face =" "verdana, Arial, Helvetica, sans-serif" "size =" "2" "> ");
SB. append (@ "<span id =" "progressbarlabel" "> Uploading... </span> ");
SB. append (@ "</font> </TD> </tr> <TD> ");
SB. append (@ "<font size =" "1" "> </font> </TD> <TD bgcolor =" "#999999 ""
Width = "" 100% ""> ");
SB. append (@ "<Table id =" "progressbar" "border =" "0" "width =" "0 ""
Cellspacing = "" 0 ""> ");
SB. append (@ "<tr> <TD style =" "background-image: url(progressbar.gif)">
<Font size = "" 1 "> </font> </TD> ");
SB. append (@ "</tr> </table> </TD> ");
SB. append (@ "<TD> <font size =" "1" "> </font> </TD> </tr> ");
SB. append (@ "<tr Height =" "5px" "> <TD colspan =" 3 "> </TD> </tr> ");
SB. append (@ "</table> ");
Writer. Write (sb. tostring ());
Base. Render (writer );
}
Private string getclientsidescript (){
System. reflection. Assembly DLL =
System. reflection. Assembly. getexecutingassembly ();
Streamreader reader;
Reader = new streamreader (DLL. getmanifestresourcestream ("progressbar.txt "));
Stringbuilder JS = new stringbuilder (reader. readtoend ());
String fp = This. Page. clientscript. getcallbackeventreference (this, "", "updateprogressbar ","");
JS. Replace ("# initiatecallback #", FP );
Reader. Close ();
Return Js. tostring ();
}
}

List 2: progressbar. js

<Script language = "JavaScript">
VaR iscompleted = false;
// This function initializes the callback to the server.
Function drawprogressbar (){
# Initiatecallback ##;
If (! Iscompleted ){
Window. setTimeout ('drawprogressbar () ', 200 );
}
Else
{
Iscompleted = false;
Document. getelementbyid ("progressbarcontainer"). style. Display = 'none ';
}
}
// When thecallback is complete, the following functions are called
Function updateprogressbar (percent ){
If (percent = 'completed '){
Iscompleted = true;
}
Else {
Document. getelementbyid ("progressbar"). width = percent;
}
}

By using the client callback function provided in ASP. NET 2.0, the progress bar control is implemented directly, because the data transmitted between the control and the client is only a simple string. However, once we add other data types to it, we will encounter mismatch between JavaScript and. Net Type Systems. Unfortunately, the implementation of callback functions in ASP. NET 2.0 does not help much. Any application that wants to use multiple data types (simple and complex) must implement a custom mode.

Fortunately, this restriction can be overcome by using an open-source Ajax. Net Library. Ajax. Net implements a proxy-based method to call server functions. Ajax. Net defines a custom attribute called ajaxmethod. When a server method is modified using ajaxmethod, a javascript-based client proxy is automatically generated by httphandler (which is part of the Ajax. Net Library. Unlike ASP. NET 2.0, it supports the string type of a single parameter for callback implementation. Ajax. Net supports multiple types such as integer, String, double-precision, datetime, and dataset.

Bertrand Le Roy recommends using Ajax. Net to handle the differences between JavaScript and. NET systems. He created a server-side control called ecmascriptobject-it re-created a javascript System Based on. NET technology. The idea is to use. Net to regenerate a client object graph. This method makes sense when the conversion occurs on the server side.

Even if we have a type of secure method to call the callback function, we still face other challenges. Javascript acts as a "glue" that combines all parts of an Ajax application. Of course, the dependence on JavaScript is also increased accordingly. Unfortunately, although Javascript is a powerful and universal language, it does not implement the object-oriented principle. This means that it may be more difficult to implement code reuse. Of course, you can use some techniques to make JavaScript look more like a traditional object-oriented language. However, even so, it is still quite difficult to implement features such as events and proxies in managed languages.

Other challenges include the lack of a reusable framework to further improve Javascript development efficiency. It may be better to have a javascript-based UI framework that can conceal the differences between different execution environments. In addition, if you can create a group of classes, they can call the Web service in a safe way (compared to manually coding soap packets and passing them using XMLHTTP.

Recently, Microsoft's Atlas project promised to focus on solving such problems. This is a great attempt to greatly simplify Ajax style development. Atlas provides a new JavaScript framework (note that the following is a preliminary announcement based on Microsoft that may change in the future)-the UI development kit. These include: common controls that support features such as drag and drop and data binding; soap stacks that call web services; browser compatibility layers that conceal differences between browsers; A client build module that includes content such as local buffering. In addition, Asp. the net team also plans to be ASP.. Net to develop other building modules, such as configuration management and member management, so that they can be used as Web service endpoints, in this way, you can directly access web services from JavaScript-for example, you can easily access personal information from the client. Finally, the Atlas project plans to extend the Javascript syntax to include interfaces, lifecycle management, and multicast events.

It is said that the next few months will be an exciting day for Ajax developers. Therefore, I very much hope that this article will arouse your interest in Ajax and give priority to this technology when you build next-generation Web applications in the future.

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.