Calling ASP.Net WebMethod using JQuery


Let’s start with web method first.

Webmethod:

1. It is very easy to write a web or page method.

2. They must be declared as “static”, because web methods are roughly equivalent to web services. In fact, the ScriptManager even calls them exactly as it would a regular web service.

3. Web or page method needs an attribute called “Webmethod”, which required to include a namespace called “System.Web.Services”.

using System.Web.Services;

[WebMethod]
public static string GetDateTime()
{
return DateTime.Now.ToString();
}

Calling a web method with jQuery:

1. As we have discussed that, web methods are equivalent to web services, It’s now very to call a web method using jQuery.

2. Before using jQuery’s method, we need to add a reference to jQuery. (Latest jQuery version is 1.10). You can even download jQuery file to locally and add a reference to your  solution. Either way will work.


<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

3. jquery ajax method to call a web method.


 $.ajax({
type: "POST",
url: "Default.aspx/GetDateTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#<%=lblDatetime.ClientID%>").text(msg.d);
},
error: function (msg) {
}
});

4. Here in my project, I have taken a button, and once you click it, web method will be called and it will display current date & time.


<asp:Button ID="btnGetDate" runat="server" Text="Get date time" OnClientClick="GetDateTime();return false;" />
<br />
<asp:Label ID="lblDatetime" runat="server" ForeColor="Red" Font-Bold="true" Font-Size="X-Large"></asp:Label>

Here is the output from my project:

Source Code Download:

Github [Repository Link]

Box.com [Direct Link to Zip file]

Call a Web Service Using JQuery in ASP.NET


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: