Using jQuery Ajax to call ASP.NET JSON web service




The jQuery Ajax infrastructure allows you to perform asynchronous HTTP requests which makes it easy to call an ASP.NET JSON web service, using this api. Let us see how.

On a side note, if you are using jQuery with ASP.NET, you will find my eBook 51 Recipes using jQuery and ASP.NET Controls helpful!

Create an ASP.NET Web service as shown below which returns a string array. You can always modify this service to make a database call or use any other data source.

using System.Web.Services;


[System.Web.Script.Services.ScriptService]

public class Names : System.Web.Services.WebService {



[WebMethod]

public string[] GetNames() {

return new string[] {

"dotnetcurry dot com",

"devcurry dot com",

"sqlservercurry dot com"

};

}

}

Observe that the method has been decorated with the [WebMethod] attribute to allow calls from client script by using HTTP POST.

Note: If a method is not marked with [ScriptMethod] attribute (which is a good practice), the method will be called by using the HTTP POST command (this is the default) and the response will be serialized as JSON. By default, ASP.NET AJAX's web services does not allow web methods to be invoked via the HTTP GET verb. Check this post by Scott Guthrie that explains why a request should be a POST request.

We will now call this web service in your ASP.NET page using jQuery, write the following code:

<html xmlns="http://www.w3.org/1999/xhtml">

<
head runat="server">

<
title>ASP.NET Service using jQuery ajax by DevCurry.com </title>

<
script type="text/javascript" src="

http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">

</
script>

<
script type="text/javascript">

$(function () {

$.ajax(

{

type: "POST",

url: "Names.asmx/GetNames",

data: "",

contentType: "application/json; charset=utf-8",

success: function (msg) {

var items = msg.d;

if (items.length > 0) {

var listItems = [];

$.each(items, function (idx, item) {

listItems.push('<option value="' +

idx + '">' + item

+ '</option>');

});

$('.lbox').append(listItems.join(''));

}

else {

alert("No records found");

}

},

error: function (XMLHttpRequest, textStatus, errorThrown) {

alert(textStatus);

}

});

});

</script>

</
head>

<
body>

<
form id="form1" runat="server">

<
div>

<
asp:ListBox ID="lb" class="lbox" runat="server" />

</
div>

</
form>

</
body>

</
html>

To consume this web service using jQuery $.ajax(), two important points to note is that the request should be a POST request and the request’s content-type must be ‘application/json; charset=utf-8’.

An object with a property ‘d’ is returned, which contains an array of objects. Once we consume this object in ‘items’, we loop through it using $.each() and add the items to the ListBox.

That’s it. When the request completes, the ListBox should be populated with data returned from the ASP.NET Webservice as shown below:

image



Will you give this article a +1 ? Thanks in advance




About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

2 Responses to "Using jQuery Ajax to call ASP.NET JSON web service"
  1. learnersreference com said...
    January 15, 2011 at 11:38 PM

    its an interesting article on ajax concept

  2. Joe Enos said...
    January 16, 2011 at 8:24 AM

    Something you may want to include - the real exciting stuff isn't when you return a string array, but when you return actual objects. You can have your method return any serializable .NET class, and the javascript will have easy access to its properties directly.

 

Copyright © 2009-2014 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions