The simple application of Ajax in ASP.net

Source: Internet
Author: User
Tags add format object end html page net string visual studio
introduce

This article describes an easy way to write Web applications using AJAX and ASP.net. At the same time, the advantages and disadvantages of using Ajax are discussed. For illustrative purposes, this article gives the corresponding JavaScript code and uses C #. NET writes the ASP.net code.

   Why use Ajax

Perhaps most people already know that Ajax means asynchronous JavaScript and XML (asynchronous JavaScript and XML). As far as I know, this technology was originally presented by Microsoft in 1999, which is known as the "Dhtml/javascript Web application using remote invocation (calls)." The core of this technology is to send an asynchronous HTTP request through the browser to invoke the server's Web page or service, and after the result is returned, the entire page can be updated without refreshing. This technology is constantly being perfected, and to this end, Web programs using Ajax are behaving much like Windows programs.

Because the implementation of this technology needs to rely on the front-end browser, it is limited in its use. But in recent years, thanks to the enhancement of browser capabilities and the performance of many AJAX-based applications such as Google and Amazon.com, the technology has finally made the Phoenix Nirvana and horny.

Ajax is now used very widely, and any dynamic Web page with a rich user experience will invariably use Ajax.

   Solution

The method of using Ajax described in this article is very simple and efficient. This approach is also very easy to maintain, and developers can implement it without any special skills, and can also be used across browsers in this way.

A basic AJAX implementation requires two main parts: a client-side HTML page written in JavaScript code that sends requests and receives responses to the server, and a remote page that can receive requests and send response information to clients. The task of the client's JavaScript code is to create a XMLHTTP object, then send the request information to the server and finally handle the response information returned by the server by way of a callback. All of this is done by JavaScript code.

The example of this article uses ASP.net program implementation, in the implementation of the following points:

1. Ajax can send requests to different service-side pages on different asp.net pages.

2. The remote page URL can contain dynamically computable parameters, which makes it easier to create a URL string in the asp.net back-end code.

3. A remote page can respond with complex data before updating an HTML page, which can also be done by asp.net back-end code.

4. A server-side page can be an extended third party page, or it can be a Web page or service of its own.

The above points are shown in Figure 1


Figure 1

   implementing the basic Ajax JavaScript approach

I split the JavaScript method into two parts: a JavaScript method that invokes a special page and a generic JavaScript method. The special method includes a callback method that is used to update the content of the page. Other AJAX methods are responsible for creating a XMLHTTP object and sending an asynchronous HTTP request to the server.

The XMLHTTP object created differs depending on the client browser. This article only considers two types of browsers: One is Microsoft's IE series browser, and the other is the Mozilla browser, including Mozilla Firefox, Netscape, and Safari. I've also tested it on opera browsers, but I can't guarantee that the code in this article will run well on opera browsers. Here's how to build the code for the XMLHTTP object:

function Getxmlhttpobject (handler)
{
var objxmlhttp = null;
if (!window. XMLHttpRequest)
{
Microsoft
objXmlHttp = Getmsxmlhttp ();
if (objxmlhttp!= null)
{
Objxmlhttp.onreadystatechange = handler;
}
}
Else
{
Mozilla | Netscape | Safari
objXmlHttp = new XMLHttpRequest ();
if (objxmlhttp!= null)
{
Objxmlhttp.onload = handler;
Objxmlhttp.onerror = handler;
}
}
return objxmlhttp;
}

function Getmsxmlhttp ()
{
var xmlHttp = null;
var CLSIDs = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.5.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0",
"msxml2.xmlhttp.2.6", "microsoft.xmlhttp.1.0",
"MICROSOFT.XMLHTTP.1", "Microsoft.XMLHTTP"];
for (var i=0; iXmlHttp = Createxmlhttp (Clsids[i]);
}
return xmlHttp;
}

function Createxmlhttp (CLSID) {
var xmlHttp = null;
try {
XmlHttp = new ActiveXObject (CLSID);
Lastclsid = CLSID;
return xmlHttp;
}
catch (e) {}
}

Since MSXML5 is only designed for office, we can not consider MSXML5. So the Getmsxmlhttp method can be simplified to the following forms:

function Getmsxmlhttp () {
var xmlHttp = null;
var CLSIDs = ["msxml2.xmlhttp.6.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0"];
for (var i=0; iXmlHttp = Createxmlhttp (Clsids[i]);
}
return xmlHttp;
}

We can see that the Getxmlhttpobject method has a handle parameter that points to a callback method, which is defined in every ASPX page that needs to be refreshed. Now that we have a XMLHTTP object, we can then send an asynchronous HTTP request.

function sendxmlhttprequest (XMLHTTP, url) {
Xmlhttp.open (' Get ', url, true);
Xmlhttp.send (NULL);
}

In the above code I used a get HTTP request to send a URL and you can easily modify the above JavaScript code to send it to other HTTP methods.

   methods written in ASPX pages

Now we've written all the methods that call the remote page. To execute these methods, we need to pass a callback method name for the Getxmlhttpobject method and then pass a URL string to the Sendxmlhttprequest method. Here is the corresponding implementation code:

var xmlHttp;

function Executecall (URL)
{
Try
{
XmlHttp = Getxmlhttpobject (Callbackmethod);
Sendxmlhttprequest (xmlHttp, URL);
}
catch (e) {}
}

Callbackmethod would fire the state
has changed, i.e. data is received back
function Callbackmethod ()
{
Try
{
ReadyState of 4 or ' complete ' represents
That data has been returned
if (xmlhttp.readystate = 4 | | xmlhttp.readystate = = ' complete ')
{
var response = Xmlhttp.responsetext;
if (Response.length > 0)
{
Update page
document.getElementById ("ElementID"). InnerHTML = response;
}
}
}
catch (e) {}
}

The Callbackmethod method is responsible for updating the page. In our example, it only updates the inner HTML of the specified HTTP object. But in practical applications, more content can be updated.

The final problem to be solved is how we call the Executecall method in the ASPX page. How you call the Executecall method depends on what this page does. In some cases, the Executecall method can be invoked when a JavaScript event departs. If you do this, we can also use the appropriate ASPX page back-end C # code to register this method as a startup script.

Page.registerstartupscript ("Ajaxmethod", String.Format ("", url) ;

We can add the above code to the Page_PreRender or Page_Load method of the ASP.net back-end code.

   Service-side pages

Let's look at what the server-side page looks like. If it's a asp.net page (we're assuming), we're just interested in its back-end code. We can delete the code in the. aspx file so that it does not affect the functionality of this ASPX page at all.

For example, we have a Web service that converts degrees Celsius to Fahrenheit. If you add a reference to the URL of this Web service to your project, Visual Studio will produce a proxy class called "Com.developerdays.ItempConverterservice" that uses the current namespace. There is an ASPX page named Gettemp.aspx that receives a query parameter called "temp" that contains the Celsius value of an integer. such as http://localhost/getTemp.aspx?temp=25. The back-end code for this ASPX page is as follows:

private void Page_Load (object sender, EventArgs e)
{
Response.Clear ();
The string temp = request.querystring["temp"];
if (temp!= null)
{
Try
{
int TEMPC = Int. Parse (temp);
String Tempf = Gettempf (TEMPC);
Response.Write (Tempf);
}
Catch
{}
}
Response.End ();
}

private string Gettempf (int tempc)
{
Com.developerdays.ITempConverterservice
svc = new Itempconverterservice ();
int Tempf = svc. Ctof (TEMPC);
return tempf.tostring ();
}

Now we're going to build a request string that can invoke the Gettemp.aspx page above, which is passed to the RegisterStartupScript method. The code is as follows:

int TEMPC = 25;
String url = String.Format ("http://localhost/" +
"Gettemp.aspx?temp={0}", TEMPC);

In some simple cases, if you want to pass a simple text, you can pass the URL directly to the Executecall method.

   Conclusions

This article presents a simple example of AJAX technology that can be used in any ASP.net program. Ajax in addition to give users some new experience, there are some shortcomings and deficiencies. As for whether to use AJAX technology, it all depends on the developers themselves, in this article I just give a simple example, learning it does not take too much time, no need for any special skills.

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.