Flag This Hub

Easy Learning: C#, ASP.NET, VB.NET, ADO.NET, .NET Framework, XML, Web Services, JQuery

By


Web Services participate an important role into data transport moreover communication between the client the server. Web services reside on the server also wait to be called by various client moreover most of the era these clients are written in server side technologies such as ASP.NET, PHP or JSP etc. ASP.NET AJAX provides web developers ability to call web services since the client part dialect such as JavaScript asynchronously to improve the user familiarity moreover to circumvent full folio refresh also postback. in this tutorial, I will show you how you can entitle an ASP.NET web service inclusive of the assist of ASP.NET AJAX.

Intended the purpose of this tutorial I have created a web service inclusive of the name ProductsService.asmx. If you are fresh to web services moreover don’t recognize how to insert web service right click active your website forename in Solution Explorer also click add new Item option also select the Web Service icon seeing as the available file templates as uncovered into figure below. A new file inclusive of the forename ProductsService.asmx will be added in your website also the code overdue file intended the web service will be added in App_Code folder.

Perceive the ProductsService amalgamation is derived seeing as the procedure.Web.Services.WebService group available in .NET Framework group library. moreover check the after directive into your code moreover make certain it is not commented because this directive is required to entitle web service utilizing ASP.NET AJAX.

[System.Web.Script.Services.ScriptService]

The implementation of web service is fairly straight onward. It encompass only one method GetProducts which is decorated inclusive of [WebMethod] attribute that is needed to expose web service methods to consumers also calling applications. The way takes category id as a parameter also revert some products based active the category. I am returning hard coded products names also not connecting database in this tutorial but you can without problems write code to revert products seeing as the database.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]
public class ProductsService : System.Web.Services.WebService
{
   [WebMethod]
   public List<string> GetProducts(int categoryId)
   {
      List<string> list = new List<string>();         

      if (categoryId == 1)
      {
         list.Add("Citrus Tingler");
         list.Add("Strawberry Shake");
         list.Add("Fruit Punch");
      }
      else
      {
         list.Add("Hot and Sour Soup");
         list.Add("Sweet Corn Chicken Soup");
         list.Add("Tomato Cream Soup");
      }     
        
      return list;
    }   
} 

To consume web service by utilizing client script you require to add an instance of the ASP.NET AJAX ScriptManager manipulate into your page. This manipulate supports a Services collection which can be used to insert the reference of web services you craving to call seeing as client part JavaScript. The ASP.NET AJAX asynchronous communication layer automatically generates JavaScript proxy classes intended each Web service reference you insert utilizing ScriptManager manipulate.

Single time your page is requested, the proxy amalgamation is downloaded to the browser at the folio load era also provides a client object that represents the exposed methods of a Web service. To call a method of the Web service, you can entitle corresponding way of generated proxy group. The proxy group in revolve communicates inclusive of the Web service asynchronously by using XmlHttpObject of the browser.

Intended this tutorial, I have added the reference of ProductsService.asmx by using <asp:ScriptReference> concern inside Services collection under the <asp:ScriptManager> element. The remaining shape encompass a DropDownList, an HTML button moreover a brand control. Notice that the onclick event of the Button1 manipulate is calling a JavaScript function Button1_onclick() which requirements to be defined into the JavaScript in your page.

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

   <asp:ScriptManager ID="ScriptManager1" runat="server">
      <Services>
         <asp:ServiceReference Path="~/ProductsService.asmx" />
      </Services>
   </asp:ScriptManager>        

   Select Category:

   <asp:DropDownList ID="DropDownList1" runat="server">
      <asp:ListItem Value="1">Mobiles</asp:ListItem>
      <asp:ListItem Value="2">Laptops</asp:ListItem>
   </asp:DropDownList>

   <input id="Button1" type="button" value="Get Products"
      onclick="Button1_onclick()" />
   <br />
   <br />
   <asp:Label ID="Label1" runat="server"></asp:Label>
</form>

As I mentioned earlier that calling a Web service method seeing as client script is asynchronous entails the communication will remove place overdue the scene also user will remain interactive inclusive of the page. If your web service returns some data you ought to provide a callback function you desire to execute active successful call to web service. You can moreover supply extra callback function to handle errors into incident the Web service call failed due to any communication or server error or Web service revert negative data.

I have added the after JavaScript code in my page to call Web service. perceive how I have called the GetProducts method of the Web service utilizing the ProductsService proxy amalgamation generated automatically for me while I have added the Web service suggestion using ScriptManager manipulate. moreover notice the callback functions onSuccess also onFailed encompass been passed as a second moreover third parameter in the proxy group GetProducts way to receive the results or error messages returned by the Web service moreover to update the folio consequently.

<head runat="server">
   <title>Consuming Web Services From AJAX</title>     

   <script type="text/javascript"> 

      function Button1_onclick() 
      {
         var categoryId = $get("DropDownList1").value;                
         ProductsService.GetProducts(categoryId, onSuccess, onFailed);
      }

      function onSuccess(result) 
      { 
         var Label1 = $get("Label1");             
         Label1.innerHTML = "";
             
         for(i=0 ; i<result.length ; i++)
         {
            Label1.innerHTML += result[i] + "<br />"; 
         }
      } 

      function onFailed(error)
      {
         var Label1 = $get("Label1"); 
         Label1.innerHTML = "Service Error: " + error.get_message();      
      }

   </script>

</head>

Now build your project and test your page in the browser.

Comments

No comments yet.

Submit a Comment
Members and Guests

Sign in or sign up and post using a hubpages account.



    Free SEO Tips

    This does not appear to be a valid RSS feed.
    Like this Hub?
    Please wait working