Tuesday, October 30, 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 http://jquery.com/


<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;)


[WebMethod()]
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) {
    jQuery.ajax({
 url: 'WebForm1.aspx/GetData',
 type: "POST",
 data: "{'userid':" + userid + "}",
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {
     alert(data.d);
 }

    });
}


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.

No comments:

Post a Comment