Different methods to call Web Services from AJAX

来源:互联网 发布:修谱软件下载 编辑:程序博客网 时间:2024/06/05 00:47

Introduction

This article briefly explains the various ways in which a Web Service method can be called using AJAX.

Background

Lots of articles are out there explaining how AJAX and Web Services interact together while trying to solve various problems. I have put together just the interaction ways. In short, here are the different ways to call a Web Service from AJAX.

Using the code

The code below demonstrates the different methods starting with the traditional approach of No AJAX as the base.

The code snippets are arranged as:

  • Web Service
  • ASPX and
  • C# code-behind

Before AJAX

This section can just be glanced over to see how a Web Service method used to be called on postback from a server control like a button.

No JavaScript - Postback required to populate Label1

 

Client ASPX:

Client code-behind:

 

Using AJAX

Method 1

This section explains how a Web Service can be called by modifying the ScriptManager.

Using AJAX - Postback not required to populate Label1

  1. Add the ScriptService() attribute to the Service class.
  2. Add the <Services> tag to the ScriptManager.
  3. Convert the server controls "Label" and "Button" to HTML controls.
  4. Call the Web Service method from JavaScript which is actually a proxy call.
  5. Remove the Click handler from the code-behind.

 

Client ASPX:

 

Client code-behind:

Method 2

This section explains how a Web Service can be called from a CascadingDropDown Toolkit control with or without the intermediate page method.

Using AJAX page method and the CascadingDropDown control from the Toolkit- Postback not required to populate the combo

  1. Add a new method to the service to return the CascadingDropDownValue[] collection. This will act as the data source for the dropdownlists.
  2. Remove the <Services> tag from the ScriptManager.
  3. Remove EnablePageMethods from the ScriptManager.
  4. Remove the label and the textbox controls.
  5. Add two DropDownList server controls and two CascadingDropDowns (from the Toolkit) to the client page.
  6. Set the service name and method of the first CascadingDropDown.
  7. Set the page method only for the second Cascadingdropdown

 

Client ASPX:

 

Client code-behind:

Points of interest

Hope this clears out a lot of confusion especially for people trying to work out how to access Web Services. I am open to comments.

原创粉丝点击