Friday, January 6, 2012

ASP.NET web method call using AJAX (jQuery)

This article is about how to call a server side function (web method) from client side (aspx page) using AJAX(provided by Jquery).

Its interesting and easy to implement. As always- lets go directly to an example and see how to implement it...

In this example we will create a webmethod which will return a message to client side

1) Create an ASP.NET Application.

2) Add a new page 'WebForm1.aspx' and make it the start up page.

3) In WebForm1.aspx include jQuery file as given below. If you do not have jQuery file, you can download the latest files from

<script src="Scripts/jquery-1.4.1.js" type="text/javascript"></script>

4) In code behind page (WebForm1.aspx.cs) create a webmethod to return some data as given below. Make sure to add the attribute [WebMethod()] to the function. You have to include the namespace System.Web.Services. (using System.Web.Services;)

public static string GetData(int userid)
    /*You can do database operations here if required*/
    return "my userid is" + userid.ToString();

5) Add script tags and include the function to call the web method. Pass the parameter (in this case 'userid') to web method as JSON object

function asyncServerCall(userid) {
 url: 'WebForm1.aspx/GetData',
 type: "POST",
 data: "{'userid':" + userid + "}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {


6) Add button on aspx page and call the ajax function on click event.

<input type="button" value="click me" onclick="asyncServerCall(1);" />

7) DONE! Run the app and click the button, you can see that the webmethod is called and data is returned.

Wasn't that easy? Let me know if you face any issue in running this example. I used Visual Studio 2010 to run this app.


DenXnis said...

Good stuff man, thanks a lot.

Swartskaap said...


Shriram Sapate said...

Nice Work Friend !

Shriram Sapate said...

How to Bind RADGridview in jQuery ajax ?

Medital said...

Thank You it works smoothly.

Phani said...

Thanks :) Its working..

Nihal Ahmad Khan said...

sir it working fine thank a lots........

Palanivel said...


KILY said...

the ajax call returns full html rather than the result of the method C#.

pedro said...

Thanks a lot man!!!

Tekslate Trainings said...

Great Work on ASP.NET AJAX
Thanks alot

Tekslate Trainings said...

Great Work on ASP.NET AJAX
Thanks Alot

Dwarakesh babu said...

Ya that's great to have blog like this it may clear the many thought from this
Pega Training
PlSQL Training
AWS Training
Teradata Training
Qlikview Training
Informatica MDM Training

Lathika Honey said...

I have read your article it's very informatic and beneficial Tibco Certification Training thanks for posting.