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]