CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
ASP.NET 3.5, AJAX and WebServices

By balamurali balaji
Posted On Mar 22,2008
Article Rating:
Average Rating: 5
No of Ratings: 1
No of Comments: 22
Category: ASP.Net
Print this article.

ASP.NET 3.5, AJAX and WebServices 

 

Introduction

 

This article explains the use of webservices in ASP.NET 3.5 AJAX environment and it tells how to call web service methods from a client-side javascript. It also outlines the new System.Web.Script namespace and explores the ways of defining the client-call to a web service method.

 

Calling WebService methods in AJAX

 

To improve the web user experience, the AJAX functionality of ASP.NET has included in its new version, new ways of calling the web service methods from client-side javascript. Without submitting or rendering a whole page, AJAX enables you to call a server-side method with no post-back.

 

The client script can make a request to a web method and pass data as input parameters to the method; and data can also be sent back to the client browser from the server.

To enable your application to call ASP.NET Web services by using client script, the server asynchronous communication layer automatically generates JavaScript proxy classes. A proxy class is generated for each Web service for which an <asp:ServiceReference> element is included under the <asp:ScriptManager> control in the page.

 

           <asp:ScriptManager runat="server" ID="scriptManagerId">

                <Scripts>

                    <asp:ScriptReference Path="CallWebServiceMethods.js" />

                </Scripts>

                <Services>

                    <asp:ServiceReference  Path="WebService.asmx" />

                </Services>

           <asp:ScriptManager runat="server" ID="scriptManagerId">

 

This proxy class is downloaded to the browser at page load time and provides a client object that represents the exposed methods of a Web service. To call a method of the Web service, you call the corresponding method of the generated JavaScript proxy class. The proxy class in turn communicates with the Web service. The requests are made asynchronously, through the XMLHTTP object of the browser.

 

<asp:ScriptReference> element is specified to register a javascript file that is to be used in a web page. Only after registering the CallWebServiceMethod.js file, you can call methods on it.

 

Calling a Web service method from script is asynchronous. To get a return value or to determine when the request has returned, you must provide a succeeded callback function. The callback function is invoked when the request has finished successfully, and it contains the return value (if any) from the Web method call. You can also provide a failed callback function to handle errors. Additionally, you can pass user context information to use in the callback functions.

 

JSONJavaScript Object Notation is the default serialization format using which data transformation takes place between client-server requests. You may disable all currently enabled protocols like HTTP-GET, HTTP-POST, and even XML-SOAP formatting used in the earlier forms of web services. The following settings in the Web.Config file just do the same.

<system.web>

    <webServices>

        <protocols>

          <clear/>

        </protocols>

      </webServices>

</system.web>

 

The figure below shows in detail the different layers that lays on both the client and server sides. A request to a web service method passes through these layers. You can see how a method is called on to one of the available proxy object and the web request is handled by an XmlHttp object on the client browser side. On the server side, your request is handled by an HTTP handler as usual and sent for XML/JSON serialization.

 

 

Example: Consuming WebService methods in AJAX

 

Consuming web service methods in AJAX involves two steps. The first step is that there is a slight change in the way you create and define web services. Making calls using client script from a page to the service methods will be the second step.

 

Step 1: Creating a web service

 

In the System.Web.Scripts.Services namespace, you may find an attribute class “ScriptSrvice” and this need to be applied to a webservice class so that the web service methods can be invoked from the client script. This would enable the proxy generation script to generate a proxy object that corresponds to the webservice class.

 

Similarly, in the same namespace, you may find another attribute class “ScriptMethod” and upon applying this attribute to a web method you can specify which HTTP verb is used to invoke a method and the format of the response. This attribute has three parameters described as below:

 

UseHttpGet: Setting it to true will invoke the method using the HTTP GET command. The default is false.

ResponseFormat: Specifies whether the response will be serialized as JSON or as XML. The default is Json.

 

XmlSerializeString: Specifies whether all return types, including string types, are serialized as XML. The value of the XmlSerializeString property is ignored when the response is serialized as JSON.

 

Ok... Now, create a new Web Site using the ASP.NET Web Service template in Visual Studio 2008 and modify the webservice class as below.

 

using System.Web.Script.Services;

 

namespace AjaxWebService

{

 

    [WebService(Namespace = "http://localhost:49232/AjaxWebService/")]

    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

    [ScriptService]

    public class Service : System.Web.Services.WebService

    {

        string myXmlData = @"<?xml version=""1.0"" encoding=""utf-8"" ?>

                <Book>

                    <Title>Programming ASP.NET 3.5, AJAX and Web Services</Title>

                </Book>";

// This method uses JSON response formatting

        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]

        [WebMethod]

        public string getNextBackupDate(int months)

        {

            return DateTime.Now.AddMonths(months).ToShortDateString();

        }

       

// This method uses XML response formatting

        [ScriptMethod(ResponseFormat = ResponseFormat.Xml)]

        [WebMethod]

        public string Greetings(string name)

                public XmlDocument GetBookTitle()

        {

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(myXmlData);

            return xmlDoc;

        }

      

// This method uses HTTP-GET protocol to call it

        [ScriptMethod(UseHttpGet = true)]

        [WebMethod]

        public string HelloWorld()

        {

            return "Hello, world";

        }

 

    }

}

 

 

Note: The web service created with ScriptService enabled as above will not be tested on the browser by default. You need to modify the settings in the Web.Config file as below to test the above webservice.

 

<webServices>

     <protocols>

       <add name="HttpGet"/>

<add name="HttpPost"/>

    </protocols>

</webServices>




 

Step 2: Call web service methods using Client Script

 

Asp.Net Web Service methods can be called from client scripts asynchronously without a postback and without refreshing the full page.  Only data is transferred between the server and client browser.

 

Currently, .NET framework 3.5 supports the web service and client web page available in the same domain (same web site). You cannot call web service methods residing on the Internet or any other system using the VS 2008 Beta 2.

 

Now add a new “Ajax Enabled Web Page” to the existing web service project and add the controls to the web page as specified in the mark-up below.

 

Write javascript functions to call the web service methods and callback methods. Calls to Web service methods are made by using the proxy class and a list of parameters, name of the succeeded callback function, the failed callback function, and the user context is passed as additional parameters in the call.

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>AJAX Web Form</title>

    <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>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:ScriptManager ID="ScriptManager1" runat="server">

        <Services>

        <asp:ServiceReference Path="~/Service.asmx"/>

        </Services>

        </asp:ScriptManager>

        <br />

        Result:&nbsp;&nbsp;         <input id="Text1" type="text" /><br />

        <br />

        <input id="Button1" type="button" value="Get Server Time" onclick="CallNextDate()" />&nbsp;&nbsp;

        <input id="Button2" type="button" value="Say Hello World" onclick="CallHelloWorld()" />&nbsp;&nbsp;

        <input id="Button3" type="button" value="Get Book Title" onclick="CallBookTitle()" />&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

        <br />

        <br />

        <br />

        </div>

    </form>

</body>

</html>

 

   

In the above markup, notice how the path attribute in the ServiceReference element of the ScriptManager control points to the web service class. This enables the Web service method to be called from script in the default.aspx page. The inline functions CallNextDate, CallHelloWorld, CallBookTitle are used to call the three web service methods. OnSuccess and OnFail methods are callback methods that get executed as the webservice method execution gets over.

 

In order to make the client web page working, you need to add the following settings to the Web.Config file.

 

<runtime>

  <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">

    <dependentAssembly>

      <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>

      <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>

    </dependentAssembly>

    <dependentAssembly>

      <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>

      <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>

    </dependentAssembly>

  </assemblyBinding>

</runtime>

 

This would redirect the ASP.NET engine to load the current version 3.5 of System.Web.Extensions.dll and other dlls to exploit the built-in AJAX support in ASP.NET 3.5.

 

Conclusion:

The ASP.NET 3.5 along with the in-built AJAX client-server framework has increased the power of using client scripts to call webservice methods. Most of the settings and javascript code files are loaded automatically when you use Visual Studio 2008. Calling web service methods in the earlier versions of AJAX, ATLAS has few troubles that make the development and debugging little difficult. Now, with ASP.NET 3.5, it has become an inherent part of the much simpler and familiar VS 2008 IDE.

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
NICE
nice
It is there
OnSucceeded is a callback function that processes the web method result and is available in the parameter 'result' as given below. You need to get the output of a webservice method using this variable.

function OnSucceeded(result)

{

var myresult = document.getElementById("Text1");

myresult.value = result;

}
how to get out parameter
i want to get the out parameter value from the web service
using onSuccess function or when i invoke a web service like this...

AjaxWebService.Service.HelloWorld(OnSucceeded);
Firefox
Hi,

Dont know if people care but I had to change

result.documentElement.text;

to

result.documentElement.textContent;

for FIrefox

Thanks to Venkman version 0.9.87.4 for introducing me to the world of debugging javascript :)
Issues adding the web service to an web application
hi Guys, i am using .Net Framework 3.5 with VS 2--8.
I first created a new project(Web application not web site). Then i added the above web service, and i am trying to call it using java script which is not working. But if i create a web site an add the above service its working.
great article
it s so simple and so great explanation.. thanx for sharing...
Not working with web application
This method does not work with .net 3.5 web application, What i have to do? But it works with web sites and not with web applications.
Why ?
NET framework 3.5 supports the web service and client web page available in the same domain (same web site).
MR
Given above artical not working in Firfox
What about XSS issues?
I'm doing something in pure javascript using a soap toolkit javascript. We have multiple app servers in our environment and most of the services live on one server. Right now we have issues with cross site scripting because we're calling from an app on AppServer1 to a service on AppServer2. It appears that the method that you describe in this post will have the same XSS issue.
Great Article
Very fine and constructive article in its category. 3.5 concepts with Ajax are very explanatory.
Synchronous way sinned!
When you call a webservice method in regular ASP.Net way, we have options of doing it in both synchronous and asynchronous ways... as the server could control both the execution of a webservice and the webservice request made by the client. When you use Javascript, on the server side, webservice methods executed asynchronously all the time as it categorically uses different callback methods for onsuccess, onfail events. Synchronous operation needs a single method that make calls, execute the server-side method and gets the value returned. This is not yet supported syntactically in Javascript but, it could be possible.
Is there any way to do this Synchronously
I know what you're going to say, "that defeats the purpose". Please humor me, and answer if you know of a way to perform these web service calls Synchronously. This would be used in a case whereby function X must precede function Y and so on. Important in financial calculations. Thanks in advance.
gsfg
fdgfd
how can I download this
When Can I download this code ?
how can I download this
When Can I download this code ?
how can I download this
When Can I download this code ?
The use of UseHttpGet
When this property is set to true, the client proxy code uses HTTP GET to call the Web service that has a URL in which each input parameter appears as a query parameter with a value. This value is obtained through JavaScript Object Notation (JSON) serialization and URL encoding of the parameter value. The use of HTTP GET for invoking the Web service method follows the same guidelines for any other Web interaction. HTTP GET should only be used for safe operations, where no sensitive data is exposed. By default, client script uses HTTP-POST to make a call to a web service operation.
Pleae explain
Hi balamurali balaji, I just wanted to know what is the use of adding [ScriptMethod(UseHttpGet = true)] attribute to the webmethod.
Nice Article
Nice article its very neat explanation!
Short n Sweet
nice intro to webservice in .net 3.5. can u pls post on securing webservice.
Good article
Thanks for the excellent article!!