Use ASP. net ajax to asynchronously call the class methods in Web Services and pages (figure)

Source: Internet
Author: User

ASP. net ajax improves the Web Service to such an important position, making it almost ASP. net ajax server logic is the most recommended implementation method, because Web Service is designed purely for business logic. As we all know, Web Service does not provide any "fancy" user interface, but focuses on the implementation of program logic with no intention. This is exactly the same as ASP. the idea of "completely separating the presentation layer from the business logic layer" advocated by the net ajax client programming model coincides with that of the client ASP. the. net ajax framework is used to process all interfaces of a program and interact with users. The server only provides pure data and does not involve any representations.

ASP. the Web Service client access proxy automatically generated by the net ajax asynchronous communication layer, that is to say, calling Web Service in JavaScript to obtain data has become an extremely simple thing-its elegance has even left us unconvinced: Can Ajax programs be written so easily?

Next, let's use a simple example program to understand how to use JavaScript to call Web Service asynchronously in ASP. net ajax applications. For the purpose of demonstration, the function of the program is very simple: you enter a name in the text box on the page, and then click the button next to it, as shown in 3-1.


Figure 3-1 enter your name on the page

The program uses the ASP. net ajax asynchronous communication layer to send the user's name to the Web Service on the server side in Ajax mode. Then the Web Service generates a greeting message based on the user name on the server side and sends it back to the client. After the client receives the server response, this greeting message is displayed, as shown in 3-2.


Figure 3-2 show the greetings from the server

Let's start with the Web Service on the server. Create a new Web Service class named SimpleWebService and declare a common Web Service method-SayHello () in it (). This method will accept a parameter named name and generate a greeting message to return:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class SimpleWebService : System.Web.Services.WebService
{
[WebMethod]
public string SayHello(string name)
{
return string.Format("Hello {0}!", name);
}
}

This is a common Web Service, and there is no difference. Do not forget to add the [WebMethod] attribute for the SayHello () method, which is required for each Web method.

To enable ASP. net ajax generates the client asynchronous call proxy for the Web Service, which allows us to directly call this method in JavaScript code. We also need to add the [ScriptService] attribute for the SimpleWebService class, which is ASP. net ajax provides additional functions for Web Services (note the bold Section in the Code ):

//…………
[ScriptService]
//…………
public class SimpleWebService : System.Web.Services.WebService
{
//…………
}

Tip: You can also directly add the [ScriptService] attribute to the Web Service method that needs to be exposed to the client without adding it to the Web Service class.

The [ScriptService] attribute is located in the System. Web. Script. Services namespace. If necessary, add the following using statement:

using System.Web.Script.Services;

The complete SimpleWebService Web Service Code is listed below. Note the bold part:

using System;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Services;
 
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class SimpleWebService : System.Web.Services.WebService
{
[WebMethod]
public string SayHello(string name)
{
return string.Format("Hello {0}!", name);
}
}

After writing the Web Service, let's test it first. The continuous testing during the development process helps to discover potential problems as soon as possible and eliminate them in the bud. If all goes well, you can see the results 3-3 when testing the Web Service.


Next, you can use ASP. net ajax to asynchronously call this Web Service. Create an ASP. NET page. Of course, you must have configured ASP. net ajax support for the Web site where the page is located. For detailed configuration methods, see volume I of this book. Add a ScriptManager Server Control on this page, which is essential for every ASP. net ajax application:

<asp:ScriptManager ID="sm" runat="server">
</asp:ScriptManager>

To enable ASP. net ajax to generate a client asynchronous call proxy for the previous Web Service, we need to add a reference to the Web Service in the ScriptManager control:

<asp:ScriptManager ID="sm" runat="server">
<Services>
<asp:ServiceReference Path="Services/SimpleWebService.asmx" />
</Services>
</asp:ScriptManager>

This declaration syntax vaguely conveys the following meaning: the client-end asynchronous call of the proxy script of Web Service will be managed by the ScriptManager control-this is natural, isn't it? ScriptManager is used to manage (manage) scripts! The detailed usage of the <Services/> label and <asp: ServiceReference/> label has been discussed in the I volume of this book.

Then declare the essential UI elements in the program interface:

<input id="tbName" type="text" />
<input id="btnInvoke" type="button" value="Say Hello"
onclick="return btnInvoke_onclick()" />
<div id="result"></div>

The <input/> with id tbName is used as the text box for the user to enter the name, and the <input/> button with id btnInvoke is used as the button, which triggers asynchronous Web Service calls; <div/> with the id of result is used to display the greeting content returned by Web Service. These IDS will be used later.

In the above Code, the btnInvoke button defines the event processing function of the click event. The implementation of this function is as follows. Note that this is the client JavaScript code:

function btnInvoke_onclick() {
var theName = $get("tbName").value;
SimpleWebService.SayHello(theName, onSayHelloSucceeded);
}

First, use $ get ("tbName"). value to obtain the text you enter in the text box. The second sentence SimpleWebService. SayHello () is to call the ASP. net ajax asynchronous communication layer to automatically generate a client proxy for SimpleWebService. This is the most important sentence in this example. Compared with the SayHello () method signature declared in the Web Service using C #, the number and order of parameters are the same, even the call syntax is nothing special-[NameSpace]. [ClassName]. [MethodName] (param1, param2 ..., CallbackFunction ). From this, we can see that the ASP. net ajax asynchronous communication layer has made great efforts and painstaking efforts to reduce developers' learning curves and improve developers' production efficiency.

Reference: for the $ get () method used to obtain DOM element references, see the introduction in Chapter 1st of this volume.

However, the client proxy also provides an additional parameter-the name of the callback function for asynchronous calls, which is onSayHelloSucceeded. This callback function will be automatically called by the ASP. net ajax asynchronous communication layer after the server-side asynchronous call returns a successful result. The code for the onSayHelloSucceeded () callback function is as follows:

function onSayHelloSucceeded(result) {
$get("result").innerHTML = result;
}

The result parameter of the onSayHelloSucceeded () callback function represents the returned result of this asynchronous call, that is, the return value of the Web Service method. Here is the greeting containing the username. This callback function will be automatically called by the ASP. net ajax asynchronous communication layer. The result parameter will also be passed in by the ASP. net ajax asynchronous communication layer, without any manual control. In the onSayHelloSucceeded () callback function of this example, we simply display this greeting in <div/> with id as result.

See ASP. the net ajax asynchronous communication layer provides more parameters and configuration functions for the client proxy automatically generated by the Web Service and corresponding callback functions. These are described in detail in this chapter.

In this way, all the code of the sample program is completed. Run the program. If everything goes well, you will see the interfaces 3-1 and 3-2.

ASP. net ajax asynchronous communication layer in this example program, looking at the implementation code of the entire example program, we can easily see the powerful functions of this architecture and careful consideration for our developers. Although in actual development, it is difficult for us to encounter such simple functions in this example program. However, although the sparrow is small and dirty, after understanding such a simple sample program, we can write different Web Services and client call code according to the actual needs during the development process, easy to complete.

Conclusion: To use ASP. net ajax to asynchronously call the Web Service on the server side in the client JavaScript, We need:

  1. Add the [ScriptService] attribute for the Web Service class or the Web Service method to be exposed to the client;
  2. Add the [WebMethod] attribute for the method that the Web Service needs to expose to the client;
  3. Add a reference to the Web Service in the ScriptManager control on the page;
  4. Use the following JavaScript syntax to call the Web Service on the client:
    [NameSpace]. [ClassName]. [MethodName] (param1, param2..., callbackFunction)
  5. Specify a callback function for the client to call asynchronously. The callback function receives the returned value and further processes it.
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.