Download Full Source Code here: [115 KB]
1. First you need to add a reference to JQuery script in your page.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
2. I have written 3 javascript functions which will call 3 different web services namely “HelloWorld”, “GetMyAllData” and “GetMyRequiredData”
function CallHelloWorld() { $.ajax({ type: "POST", url: "MyWebService.asmx/HelloWorld", data: "", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { $("#<%=lblHelloWorld.ClientID%>").text(response.d); }, error: function (jqXHR, textStatus, errorThrown) { //handle error here } }); }
function CallGetMyAllData() { $.ajax({ type: "POST", url: "MyWebService.asmx/GetMyAllData", data: "", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { $("#<%=lblGetMyData.ClientID%>").text(response.d); }, error: function (jqXHR, textStatus, errorThrown) { //handle error here } }); }
function CallGetMyRequiredData() { $.ajax({ type: "POST", url: "MyWebService.asmx/GetMyRequiredData", data: "{'count': '" + 2 + "'}", contentType: "application/json; charset=utf-8", dataType: "json", success: function (response) { $("#<%=lblGetRequiredData.ClientID%>").text(response.d); }, error: function (jqXHR, textStatus, errorThrown) { //handle error here } }); }
Jquery Ajax syntax explained:
type – this means how do you post your data to server by using GET or POST http methods
url – the path to the web service (asmx file) or webmethod
data – input parameters for web service method (Here in our example “GetMyRequiredData” web service requires an input parameter namely “Count”)
contentType or dataType – type of data that you’re sending and expecting back to and from the server
success – result received successfully
error – error receiving result back from server
For more details about Jquery Ajax, Please refer following link:
http://api.jquery.com/jQuery.ajax/
3. Following are the 3 different web services.
WebService Code Snippet:
[WebMethod] public string HelloWorld() { return "Hello World"; } private List<string> GetData() { List<string> collection = new List<string>(); collection.Add("Pune"); collection.Add("New York"); collection.Add("London"); collection.Add("Moscow"); collection.Add("Sydney"); return collection; } [WebMethod] public List<string> GetMyAllData() { return GetData(); } [WebMethod] public List<string> GetMyRequiredData(string count) { List<string> data = new List<string>(); List<string> fullData = GetData(); for (int index = 0; index < Convert.ToInt32(count); index++) { data.Add(fullData[index]); } return data; }
Output will look like this:
3 comments