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]

9 thoughts on “Calling ASP.Net WebMethod using JQuery

  1. Incase of .NET framework 2.0, the above snippet is not working. It is returing whole html code instead of datetime.

    Any suggestions for framework 2.0 to make it work?

    Like

    1. System.Web.Extension.dll is the main DLL that performs this magic!!

      You need to install ASP.NET AJAX Extensions.
      http://www.microsoft.com/en-in/download/details.aspx?id=883

      The default directory of installation is “Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025”.

      Add a reference to System.Web.Extensions.dll in your .NET 2.0 project.

      You can refer following link for details:
      http://www.codeproject.com/Articles/45275/Create-a-JSON-WebService-in-ASP-NET-2-0-with-a-jQu

      Like

  2. Great web site you’ve got here.. It’s hard to find quality writing
    like yours nowadays. I seriously appreciate people like you!
    Take care!!

    Like

Leave a comment