Use Ajax and Web Service Development instances of ASP. Net 3.5

Source: Internet
Author: User

Here, I also introduced the namespace System. Web. Script method to determine how the client calls the Web service.

Calling Web service methods in AJAX can improve the Web user experience. AJAX in NET3.5 has added its new features. The new features can be used from the client JavaScript to call Web service methods without refreshing the entire page. AJAX technology allows you to call methods on the server without post back. Client scripts can be used to propose a Web method of the request, and data can be used as input parameters or sent back from the server to the client browser.

In order for your application to call ASP. NET Web service to use client scripts, the server asynchronous communication layer will automatically generate JavaScript proxy classes. The proxy class is generated as an element of each Web service to be included in the control page.

 <asp:ScriptManager id=scriptManagerId runat="server">     <SERVICES>            <asp:ServiceReference Path="WebService.asmx"></asp:ServiceReference>     </SERVICES></asp:ScriptManager>

This is the download proxy browser loading time on the Web page, and provides a client object, proxy call method Web service. The JavaScript proxy class generated when the corresponding method is called. This proxy class enables communication and network services. These requests are asynchronously communicated through the XMLHTTP Object Browser.

As shown in, the communication frameworks for clients and servers on different layers are defined in detail.

498) this. style. width = 498; "border = 0>

The element is used to register a JavaScript file on a webpage. You can call methods only when registering the CallWebServiceMethod. js file. The scripts that call Web service methods are asynchronous. You must provide a successful callback function to obtain the return value or determine when to return the request. When a callback function is called, the request has been successfully completed and the returned values include, if any, are called from the Web method. You can also provide a failed callback function to handle errors. In addition, you can use the callback function in the background information of the user.

For example, it is the time sequence diagram for calling Web service through WCF and Ajax.

498) this. style. width = 498; "border = 0>

As mentioned in the previous article, JSON Extension Application Based on ASP. NET 3.5 Web Service), the JSON-JavaScript Object symbol is the default serialization format, which is used for client server requests between data conversions. You can disable all currently enabled protocols such as HTTP-GET, HTTP-POST, or even XML-format SOAP that are used in earlier forms of Web Services. The following settings are also used in the Web. config file.
 <SYSTEM.WEB>    <WEBSERVICES>        <PROTOCOLS>          <CLEAR />        </PROTOCOLS>      </WEBSERVICES></SYSTEM.WEB> 

Request a Web service method through these layers. You can see how to use a method that requires an XMLHttp object to run on the client browser side in an available proxy object and Web request. On the server side, your request is serialized in XML/JSON format by an HTTP handler as usual.

As shown in, asp.net 3.5 calls the class relationship diagram between Ajax and Web services.

498) this. style. width = 498; "border = 0>

Using Web Services in AJAX involves two steps: the first step is to create and define Web Services. The second step is to use the client script to call a service from a webpage. Create a Web Service:

In the System. Web. Scripts. Services namespace, you may find an Attribute Class "ScriptSrvice", which must be applicable to the Web service class so that the Web service method can call Scripts from the client. This generates a script generated by the proxy to generate a proxy object corresponding to the Web service class.

Similarly, in the same namespace, you may find another property class "ScriptMethod". If you use this property as the Web method, you can specify which HTTP verbs are used to call a method and Response Form.

The attribute has the following three parameters:

UseHttpGet: if it is set to true, this method is called to use the http get command. The default value is false.

ResponseFormat: Specifies whether to respond to the serialized JSON or XML. The default value is JSON.

XmlSerializeString: Specify whether all return types, including string types, are serialized JSON values serialized for XML values that will be ignored in the XmlSerializeString continuous response.

Now, create a new Web Using ASP. NET Web Service template in Microsoft Visual Studio 2008 and modify the Web Service class as follows:

using System.Web.Script.Services;namespace AjaxWebService{    [WebService(Namespace = "http://localhost:1382/AjaxWebService/")]    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]    [ScriptService]    public class Service : System.Web.Services.WebService    {        string myXmlData = @"<?xml version=""1.0"" encoding=""utf-8"" ?>                <BOOK>                                    </BOOK>";               /// <SUMMARY>        /// This method uses JSON response formatting         /// </SUMMARY>        /// <PARAM name="months"></PARAM>        /// <RETURNS></RETURNS>        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]        [WebMethod]        public string getNextBackupDate(int months)        {            return DateTime.Now.AddMonths(months).ToShortDateString();        }                /// <SUMMARY>        /// This method uses XML response formatting        /// </SUMMARY>        /// <RETURNS></RETURNS>        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]        [WebMethod]        public XmlDocument GetBookTitle()        {            XmlDocument xmlDoc = new XmlDocument();            xmlDoc.LoadXml(myXmlData);            return xmlDoc;        }               /// <SUMMARY>        /// This method uses HTTP-GET protocol to call it        /// </SUMMARY>        /// <RETURNS></RETURNS>        [ScriptMethod(UseHttpGet = true)]        [WebMethod]        public string HelloWorld()        {            return "Hello, world";        }    }}

Note: The ScriptService created by the Web service will not be used by the browser by default if it is used. You need to modify the settings Web. config file in the file as follows to test the preceding Web service.

 <WEBSERVICES>     <PROTOCOLS>       <ADD name="HttpGet" />        <ADD name="HttpPost" />    </PROTOCOLS></WEBSERVICES>

The client script is used to call the Web service method. The Asp. Net Web service method asynchronously does not return data from the client script and does not refresh the entire page. Only the server that transmits data between them and the browser of the client.
Currently, the. NET 3.5 framework supports Web Services and client Web pages that can be on the same website in the same domain ).

Now add a new "Ajax activation Web page", write JavaScript Functions to call Web Services and callback methods using an existing Web Service Project and add the tag specified in the webpage of the control as follows. You can call a Web service by using the proxy class and parameter list, the name of the successful callback function, and the failed callback function. You can call this function by calling additional parameters.

<%@ Page  Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="AjaxWebService.Default" %><HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD runat="server">        <SCRIPT type=text/javascript>function CallNextDate()     {        AjaxWebService.Service.getNextBackupDate(1, OnSucceeded);    }    function CallHelloWorld()     {        AjaxWebService.Service.HelloWorld(OnSucceeded);    }   function CallBookTitle()     {        AjaxWebService.Service.GetBookTitle(OnSuccess, OnFail, "XmlDocument");    }        // This is the callback function that processes the Web Service return value in JSON format.    function OnSucceeded(result)    {        var myresult = document.getElementById("Text1");        myresult.value = result;    }       // This is the callback function that processes the Web Service return value in XML format.    function OnSuccess(result)    {        var myresult = document.getElementById("Text1");        myresult.value = "Title: " + result.documentElement.text;    }       // This is the callback function that processes the Web Service return value in XML format.    function OnFail(error)    {        var myresult = document.getElementById("Text1");        myresult.value = "Service Error: " + error.get_message();    }     </SCRIPT>      <STYLE type=text/css>        #Text1        {            width: 375px;        }        #Button2        {            width: 140px;        }    </STYLE>    <FORM id=form1 runat="server">    <DIV>        <asp:ScriptManager id=ScriptManager1 runat="server">        <SERVICES>        <asp:ServiceReference Path="~/Service.asmx"></asp:ServiceReference>        </SERVICES>        </asp:ScriptManager>        <BR>        Result:           <INPUT id=Text1><BR>        <BR>        <INPUT id=Button1 onclick=CallNextDate() type=button value="Get Server Time">          <INPUT id=Button2 onclick=CallHelloWorld() type=button value="Say Hello World">          <INPUT id=Button3 onclick=CallBookTitle() type=button value="Get Book Title">             <BR>        <BR>        <BR>        </DIV>    </FORM>

The above mark shows how the notification path property is directed to the Web service class at the ServiceReference element ScriptManager control point. This makes the Web service method called the default. aspx page in the script.

The embedded CallNextDate, CallHelloWorld, and CallBookTitle functions are used to call three Web service methods. The OnSuccess and OnFail methods are the callback methods, and the Web service method to be executed is executed. To make the webpage of the client work normally, you need to add the Web. config file set below.

 <RUNTIME>    <ASSEMBLYBINDING xmlns="urn:schemas-microsoft-com:asm.v1">      <DEPENDENTASSEMBLY>        <ASSEMBLYIDENTITY name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35" />        <BINDINGREDIRECT newVersion="3.5.0.0" oldVersion="1.0.0.0-1.1.0.0" />      </DEPENDENTASSEMBLY>      <DEPENDENTASSEMBLY>        <ASSEMBLYIDENTITY name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35" />        <BINDINGREDIRECT newVersion="3.5.0.0" oldVersion="1.0.0.0-1.1.0.0" />      </DEPENDENTASSEMBLY>    </ASSEMBLYBINDING>  </RUNTIME>

This article uses the System. Web. Extensions. dll and other DLL referenced by Microsoft ASP. NET 3.5, and uses the AJAX technology built in ASP. NET3.5 for your reference only.

Edit recommendations]

  1. 10 tips for ASP. NET application design
  2. Detailed description of the Request lifecycle of ASP. NET MVC
  3. Analysis on ASP. NET global Exception Handling

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.