Use ASP. net ajax to asynchronously call the class methods in Web Services and pages (1): Call Web Services and call class methods on pages)

Source: Internet
Author: User

This article is from ASP.. net ajax programming Chapter II: client-related Microsoft AJAX Library Chapter III asynchronous call of Web Services and class methods on pages. For more information, see other articles in this chapter.

3.1CallWeb Service

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.

Figure 3-3 Web service testing page

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.

3.2Call the class methods on the page

It seems a good idea to allow client JavaScript to directly call the Web Service on the server end asynchronously-this should be the case for an idealized layered Ajax application! However, as ASP. NET server-side development model is "Spoiled". A more familiar method is to write the method directly in ASP. NET page. For example, the code that processes the Click Event of a server button on the page may call the method defined in the same page code file as follows:

protected void Button1_Click(object sender, EventArgs e)
{
    myLabel.Text = this.GetTextForLabel();
}
 
public string GetTextForLabel()
{
    // ......
    return "Some Text";
}

For the "legacy" ASP. NET applications, it is quite common to define the methods directly on the ASP. NET page. It would not be very troublesome to migrate these methods to Web services one by one just to access Web Service functions with ASP. net ajax clients?

Fortunately, ASP. net ajax takes this issue into consideration during design and provides us with an alternative. ASP. net ajax asynchronous communication layer can be declared in ASP. NET page (static, VB.. NET.

We still use an instance program to understand this function. The functions and interfaces of the sample program are exactly the same as those in the previous section. The only difference is that the asynchronous client call is not a Web Service, but is defined in ASP.. NET page.

The first is to define the class methods on the ASP. NET page. The complete method declaration is as follows:

[WebMethod]
public static string SayHelloFromPage(string name)
{
    return string.Format("Hello {0}!", name);
}

Note that if you want ASP. net ajax to generate a client call proxy for it, you must add the [WebMethod] attribute for this method.

The ScriptManager control is followed. Note that the EnablePageMethods attribute is set to true in the bold code, which is also required for the client to directly call the Server Page method. If you forget to set this property, the program will not be able to complete the expected functions:

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

The UI element in the program interface is exactly the same as the sample program in the previous section, which is not mentioned here:

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

In this example, the click event processing function of the buttons and the callback function of asynchronous calls must be modified as follows:

function btnInvoke_onclick() {
    var theName = $get("tbName").value;
    PageMethods.SayHelloFromPage(theName, onSayHelloSucceeded);
}
 
function onSayHelloSucceeded(result) {
    $get("result").innerHTML = result;
}

Note the bold part in the above Code. You can see that the unified prefix for calling the PAGE method proxy is PageMethods. Next is the name of the page method, which is SayHelloFromPage (). The parameter list is consistent with the definition of the method in C #. An additional parameter indicates the callback function of this asynchronous call. That is, the syntax is:

PageMethods.[MethodName](param1, param2 …, callbackFunction);

In this way, the sample program is completed. After running the program, we will see the same interface as 3-1 and 3-2.

Summary: to use ASP. net ajax to asynchronously call methods defined in ASP. NET pages in client JavaScript, We need:

  1. Declare this method as public );
  2. Declare this method as a class method (static in C #, Shared in VB. NET), instead of an instance method;
  3. Add the [WebMethod] attribute for this method;
  4. Set the EnablePageMethods attribute of the ScriptManager control on the page to true;
  5. Call the PAGE method using the following JavaScript syntax on the client:
    PageMethods. [MethodName] (param1, param2 ..., CallbackFunction );
  6. Specify a callback function for the client to call asynchronously. The callback function receives the returned value and further processes it.

From: http://www.cnblogs.com/dflying/archive/2007/06/05/771490.html

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.