Deborah's Developer MindScape






         Tips and Techniques for Web and .NET developers.

September 24, 2012

Building a JavaScript Client for a Web API Service

Filed under: ASP.NET,ASP.NET Web API,C#,JavaScript,VB.NET @ 12:54 am

An ASP.NET Web API service provides support for many different types of client applications. One such client is a JavaScript application. This post provides a very simple JavaScript client you can use to test your Web API service.

[See this prior post for an introduction to building an ASP.NET Web API service. The service created in that post is the example service used here.]

Here is the HTML/JavaScript code to display all of the key/value pairs for a single object returned by a Web API service.

<!DOCTYPE html>
<html lang=”en”>
<head>
<title>Customer Information</title>
<script src=”../../Scripts/jquery-1.7.1.min.js”
type=”text/javascript”></script>
<script type=”text/javascript”>
$(document).ready(function () {
// Send an AJAX request for Customer Info
$.getJSON(“api/customer/2”,
function (data) {
// On success, ‘data’ contains the customer details.
$.each(data, function (key, val) {
// Format the text to display.
var str = key + ‘: ‘ + val;

                    // Add a paragraph for each property.
$(‘#info’).append(‘<p>’ + str + ‘</p>’);
})
})

             // Handle a fail
.fail(
function (jqXHR, textStatus, err) {
$(‘#info’).html(‘Error: ‘ + err);
});
});
</script>
</head>

<body>
<div>
<h1>Customer Account Information</h1>
<p id=’info’ />
</div>
</body>

</html>

If you followed the prior post mentioned above and built the sample Web API service, you can delete all of the code from the Index.cshtml file and replace it with the above code.

When you run the application, you get this:

image

Let’s go through the JQuery script code. The example uses the 1.7.1 version of JQuery. The script itself does the following:

  • $.getJSON: Gets the JSON format of the data returned when passing “api/customer/2” to the Web API service. You can change the url string passed to the service to match any url accepted by your service.
  • $.each: Iterates over each object, executing a function for each one. In this case, it processes each name/value pair provided by the JSON format.
    • It builds a string with the name of the field, a colon, and the value.
    • It adds the string to a paragraph element and then appends the paragraph to an element with an Id of #info.
  • .fail: Provides error information if an error is returned by the service.

The HTML code displays the header and a paragraph placeholder that is extended by the script.

If you want to display a set of business objects with their name/value pairs, you can change the script as follows:

<script type=”text/javascript”>
$(document).ready(function () {
// Send an AJAX request for Customer Info
$.getJSON(“api/customer”,
function (data) {
// On success, ‘data’ contains the customers details.
$.each(data, function (key, row) {

                $(‘#info’).append(‘<p>’ + ‘Item: ‘ + key + ‘</p>’);
// Process each customer (“row”)
$.each(row, function (rowKey, rowValue) {

                    // Format the text to display.
var str = rowKey + ‘: ‘ + rowValue;

                    // Add a paragraph for each property.
$(‘#info’).append(‘<p style=”text-indent: 5em;”>’
+ str + ‘</p>’);
})
})
})

         // Handle a fail
.fail(
function (jqXHR, textStatus, err) {
$(‘#info’).html(‘Error: ‘ + err);
});
});
</script>

This script includes two .each methods, the first one processes each customer and the second one processes each field of the customer from the JSON.

The result of this script is shown below:

image

Notice that both scripts could be used for any set of JSON objects returned from a Web API service. You just need to change the url string as appropriate for the service.

Enjoy!

1 Comment

  1.   Rubaiyat — September 24, 2012 @ 5:59 am    Reply

    Really, it’s helped me.

RSS feed for comments on this post. TrackBack URI

Leave a comment

© 2019 Deborah's Developer MindScape   Provided by WPMU DEV -The WordPress Experts   Hosted by Microsoft MVPs