How to create an Ajax enabled Web Service in ASP.Net

In this post I will try to show you with a detailed example how to create an Ajax enabled Web Service and consume it from client scripts running in a different Web site. It will be a simple example but the principles apply to the most complicated ones.

I will use Visual Studio 2010 Ultimate edition. You can use Visual Studio 2008 as well. VS 2010/2008 express editions will suffice for this example.

I will use VB.net as the development language.

1) Fire VS and use the Web Service template to create a web service application and save it in the local IIS and not in the local filesystem.

Create in the local IIS a new Web Application called CalculateWebService.

2) Delete the Service.vb file and the Service.asmx file.

3) Add in your web service project a new web service (Add->New item) and call it Calculate.asmx

4) In oder to allow this Web Service to be called from script, using ASP.NET AJAX we must add this line of code in the Calculate.vb file


<System.Web.Script.Services.ScriptService()> 

 5) Add a namespace just after the Imports statements. I have called it Calculus. You can name it as you want.Place all the code for the web service inside the Namespace.

Namespace Calculus

'Code goes here

End Namespace

6) Update the Calculus.asmx file to reflect the changes. It should look like that

<%@ WebService Language="VB" CodeBehind="~/App_Code/Calculate.vb" 
Class="Calculus.Calculate" %>
 

7) Comment out the HelloWorld() function and add another one that adds 2 integers. Do not comment out the

<WebMethod()>

So our new little function should look something  like this.

  Public Function Add(ByVal a As IntegerByVal b As IntegerAs String

            Dim myresult As String
          
            Dim res As Integer

            res = a + b
            myresult = res.ToString()

            Return myresult


        End Function

8) Test your web service by viewing it in the browser. If evertything is working fine we should create the application that will consume this web service.Copy the web service URL in a notepad.You will need it shortly.

In my case is http://localhost/CalculateWebservice/Calculate.asmx

9) Close your web service project and create a new web site in your local IIS. Create a new web application and name it ConsumeCalculus.

Have a look at the picture below - click on the image to enlarge


 10 ) Inside the <form> tags we can have markup that looks like this

    
        First Number:<input type="text" id="txtnuma"/><br />
        Second Number:<input type="text" id="txtnumb" /><br />
        <button id="CalculusButton">ADD</button><br />
        <span id="additionres"></span>   

 11) In order to be able to call the web service we should add a ScriptManager control and make it aware of that service. The code should be inside the form element.

  So your code should look something like that.Paste the code in the notepad in the Path attribute.

    <asp:ScriptManager>
    
    <Services>
<asp:ServiceReference 
Path="http://localhost/CalculateWebservice/Calculate.asmx"  />
    
  </Services>
    
    </asp:ScriptManager>
    First Number:<input type="text" id="txtnuma"/><br />
    Second Number:<input type="text" id="txtnumb" /><br />
        <button id="CalculusButton">ADD</button><br />
        <span id="additionres"></span>
 

 12) We should call the web service from our button. The javascript method we want to call when this button is clicked is

   "OnCalculusClick()"

 13) So the complete markup for the button is

<asp:Button Text="Submit" ID="btnadd" runat="server" 
OnClick="OnCalculusClick();return false;" />

 14) Inside the <head> section of our page we have to write the Javascript code. Our complete code looks like this

<script type="text/javascript">
     
     function OnCalculusClick() 
        
    {
        Calculus.Calculate.Add($get("txtnuma").value, $get("txtnumb").value,
             OnCalculusComplete);
    }

    function OnCalculusComplete(result) 
    
    {
        var myres = $get("additionres");
        myres.innerHTML = result;
    }
    </script>

I will explain what we did in the code above. we did create our first Javascript function OnCalculusClick() .

We must call the web service and must know the name of the web method, so we add this bit of code

Calculus.Calculate.Add($get("txtnuma").value, $get("txtnumb").value,
             OnCalculusComplete);

 

The name of the namespace, the name of the web service class and the name of our web method comprise the qualified name, thus Calculus.Calculate.Add

 

Then we get the values from the textboxes using $get which is short for document.getElementByID . We do have another parameter(OnCalculusComplete method) and it is required by our client. This method will be called asynchronously. This is called a callback method.

Then we add a new function OnCalculusComplete. This is going to receive a parameter which is the result of the web method. So the result will be the string that our web service returns.

Then I just get the value that the web service returns and assign it to my <span> element that has an ID of "additionres".

15) Run your application, fill in the textboxes with integers and hit the button. Then you will be able to see the result that comes straight from the web service.

Email me if you need the code.

Hope it helps!!!

 

1 Comment

Comments have been disabled for this content.