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.
 
Asynchronous Access To WebService using ScriptManager in Asp.Net Ajax

By Suresh Kumar Goudampally
Posted On Feb 21, 2011
Article Rating:
Be first to rate
this article.
No of Comments: 0
Category: ASP.Net AJAX
Print this article.

Asynchronous Access To WebService using ScriptManager in Asp.Net Ajax

Introduction

Normally when we want to access the web service asynchronously using javascript, we need to write the client side javascript framework which runs some hundreds of lines of code. This makes the developer job tougher with the issues like maintenance, exception handling and requires many man hours to achieve this. Microsoft Ajax framework provides the utilities via ScriptManager to access the web services from javascript code. Using the ScriptManager of the Microsoft Ajax the developer job is made easy to access the webservice asynchronously from javascript. In this article I will be discussing how the ScriptManager can be leveraged for accessing the webservice from the client code javascript.

Samples Demonstrating Accessing WebService Which is in same Domain

Lets’ call a sample webservice using the scriptmanager. Here are the steps.

1.      First take an Ajax WebApplication and drag the ScriptManager to the Webform

2.      Now add a WebService WebService1.asmx in the same application and same folder where the webform is. Write a method HelloWorld which returns “Hello Suresh Kumar Goudampally”. Assign the webservice class with [System.Web.Script.Services.ScriptService()]

[System.Web.Script.Services.ScriptService()]

     public class WebService1 : System.Web.Services.WebService

     {

        [WebMethod]

        public string HelloWorld()

        {

            return "Hello Suresh Kumar Goudampally";

        }

}

3.      Now add the newly added WebService to the scriptmanager reference. The markup looks as below.

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

            <Services>

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

      </Services>       

   </asp:ScriptManager>   

 

4.      The Scriptmanager takes the webservice reference path as input and renders the required client side proxy to access the webservice. Drag a Button control on to the webform and using javascript call the clientside proxy method rendered by the Scriptmanager. The markup looks as below.

<asp:Button OnClientClick="return fun()" ID="Button1" runat="server" Text="Call WebService From Client Code" Width="260px" /></div>

                        function fun()

              {           

ScriptManagerWebServices.WebService1.HelloWorld(OnSuccess, OnFailure, OnTimeOutError);

            );

            return false;

              }

      function OnSuccess(response)

              { 

                     alert(response);

              }

              function OnFailure(response)

              {

                     alert("Error:" + response._message);

              }

 

Note: Here ScriptManagerWebServices is the namespace of webservice and WebService1 is the name of the webservice class.

5.      Run the application and check the output.

 

Accessing a WebService which is in different Domain

In the previous example we have seen accessing the webservice method which is in the same app domain of the webapplication. We can also access the webservice which is hosted separately.

1.      Take a new webservice application and let’s say we have method which returns the list of the student names. Assign the required attributes for the class and the webmethod.

[System.Web.Script.Services.ScriptService()]

       public class Service1 : System.Web.Services.WebService

       {

        [WebMethod]

        public string[] GetStudentsList()

        {

            string[] strStudents = new string[4];

            strStudents[0] = "Suresh Kumar Goudampally";

            strStudents[1] = "Satheesh Babu";

            strStudents[2] = "Bharath Kumar Goudampally";

            strStudents[3] = "Sravan Kumar Goudampally";

            return strStudents;

        }

 }

 

2.      Here in the web.config of the webservice application we need to set all the settings required by the Ajax WebApplication.

The sample web.config looks like this

<?xml version="1.0"?>

<configuration>

  <configSections>

    <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="MachineToApplication"/>

<sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35">

<section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" allowDefinition="Everywhere" />         

        </sectionGroup>

      </sectionGroup>

    </sectionGroup>

  </configSections>

  <system.web>   

    <pages>

      <controls>

        <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

      </controls>

    </pages>   

    <httpHandlers>

      <remove verb="*" path="*.asmx"/>

      <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>

<add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/>

    </httpHandlers>

  </system.web

</configuration>

 

3.      Now add the webservice reference to the ScriptManager and the sample markup is shown below.

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

            <Services>

<asp:ServiceReference Path="http://localhost/WebServiceTest/Service1.asmx" />

            </Services>       

</asp:ScriptManager>

 

4.      Call the client side proxy generated by the ScriptManager on the button click.

<asp:Button OnClientClick="return fun()" ID="Button1" runat="server" Text="Call WebService From Client Code" Width="260px" /></div>

 function fun()

        {     

WebService1.Service1.GetStudentsList(OnSuccess, OnFailure, OnTimeOutError);

            return false;

  }

 

Here WebService1 is the namespace of the webservice application and the Service1 is the name of the class 

5.      Run the application and check the output.


 

Programmatically Adding WebService references to ScriptManager

We can also add webservice paths to ScriptManger programmatically as shown below.

ServiceReference webref = new ServiceReference();

      webref.Path = "http://localhost/WebServiceTest/Service1.asmx";

      ScriptManager1.Services.Add(webref);

 

Javascript Proxy

The javascript proxy is created by scriptmanger dynamically and rendered to the client in the following way. For the above example the javascrip proxy is rendered in the following way.

<script src="http://localhost/WebServiceTest/Service1.asmx/jsdebug" type="text/javascript"></script>

 

We can also make the javascript proxy embeded directly on to the page make making inline script to “true”

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

            <Services>

 <asp:ServiceReference InlineScript="true" Path="WebService1.asmx" />               

            </Services>       

</asp:ScriptManager>

 

The InlineScript=true can be applied only to webservice which are in the same app domain.

 




Accessing WCF web services

We can also accesss the WCF webservices in the similar way provided all the required http handlers and httpmodules are switched on web.config file of WCF webservice application as discussed above.

 

CallBack Methods and their significance

 

We can pass parameters to webservice and then use callback methods for updating the browser elements. We can pass the references to the three callback methods to call when the webservice returns the response. The two callback methods are:

Ø       onSuccess

Ø       onError

 

As we discussed we need to have callback function for success webservice call and for unsuccessful webservice call. Unsuccessful webservice call means if there is an internal server error on the webservice.

Using the callback method we can fetch the required result from the webservice and use it on the client script as required.

function onSucceed(results, currentContext, methodName)

{

      alert(results);

}

 

function onError(results, currentContext, methodName)

{

      alert(results);

}

 

The method names and parameter names are user defined.  We can use any name for the callback methods and their parameters.

The OnSucceed parameter indicates the javascript function to be called when the call has succeeded and the result parameter has the result stored in it. In our case the string returned from the webservice.


The OnError parameter indicates the javascript function to be called when error occurs. The success call back method has three parameters:

Ø       Result – Returns the output of the page method.

Ø       currentContext – This is used to handle different logic when single callback is used for multiple page method requests. We can also pass array of values as userContext parameter.

Ø       methodName – This parameter returns the name of  page method called.

Ø      The error call back method has three parameters:

Ø       Result – Returns the output of the page method.

Ø       currentContext – This is used to handle different logic when single callback is used for multiple   page method requests. We can also pass array of values as userContext parameter.

Ø       methodName – This parameter returns the name of  page method called.

Ø       The result here returns the type of the error, stack trace, message and type of the exceptions. You can display the required information to the end user using the following   methods of error object

get_exceptionType()

get_mesage()

get_stackTrace()

get_statusCode()

get_timedOut()

 

function onError(result)

{

      alert(result.get_message());

}    

         

Sending the userContext parameter

var contextArray = "u1";     

WebService1.Service1.GetStudentsList(onSucceed, onError,contextArray);  

And this can be used on the call back to execute different logic

function onSucceed(result,userContext,methodname)

      if (userContext = “u1”)

      {

            alert(result);

      }

}

 

References

http://msdn.microsoft.com/en-us/library/bb398998.aspx

http://msdn.microsoft.com/en-us/magazine/cc163354.aspx#S3

http://www.asp.net/ajax/tutorials/understanding-asp-net-ajax-web-services

 

Conclusion

In this article I mainly explained how easily we can communicate with webservices asynchronously via javascript using the ScriptManager. There are many aspects which I did not cover in this article like exception handling, communicating with WCF web services, the return types supported and so on which I will covering in further articles. Happy Reading!!!

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments