Join Dotnetcodes DotnetCodes.com is online Discussion Forum for Software professionals . It lets you find friends around the world and Create professional network that share similar interests as you. Get help on ur projects by industry specialists. Also get answers to all ur technical/placement related querries.Get an edge over others.
Already MemberClick here to login
ASP.net MVC Interview Questions Answers Interview Questions
Get Started Developing for Android Apps with Eclipse Articles
Whats New in ASP.NET 4.0 Part 2 Articles
.Net framework 4.0 Interview Questions Answers Interview Questions
SQL server reporting services Interview Questions (SSRS) part 1 Articles
SharePoint 2010 interview Questions Answers Interview Questions
Html5 interview questions and answers Interview Questions
Serial Number in SSRS Articles
How to Print a Crystal Report direct to printer Articles
Explaining SDLC -System Development Life Cycle Articles
Populate or bind Dropdownlist in Asp.net using Jquery and Json Articles
Sql Server Database Backup and Restore through C# Source Codes
ASP .Net Page Life cycle Articles
Benefits of Generics in .net Articles
.Net framework 4.0 major improvements Articles
Submit Articles | More Articles..

Learn How to call Web API with JavasScript and jQuery

Posted By: rakesh On:12/18/2013 11:40:49 PM in:Articles Category:ASP.NET MVC Hits:643
In this article we will learn how to call the Web API with JavasScript and jQuery

Introduction

In this context, we'll add an HTML page that uses AJAX to call the web API. We'll use jQuery to make the AJAX calls and also to update the page with the results.

Before we proceed have a look at Learn How to create ASP.NET Web API as this was the continuation of it. 

In Solution Explorer, right-click the project and select Add, then select New Item.

In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "index.html".

Replace everything in this file with the following:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>Product App</title>
</head>
<body>

  <div>
    <h2>All Products</h2>
    <ul id="products" />
  </div>
  <div>
    <h2>Search by ID</h2>
    <input type="text" id="prodId" size="5" />
    <input type="button" value="Search" onclick="find();" />
    <p id="product" />
  </div>

  <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
  <script>
    var uri = 'api/products';

    $(document).ready(function () {
      // Send an AJAX request
      $.getJSON(uri)
          .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
              // Add a list item for the product.
              $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
          });
    });

    function formatItem(item) {
      return item.Name + ': $' + item.Price;
    }

    function find() {
      var id = $('#prodId').val();
      $.getJSON(uri + '/' + id)
          .done(function (data) {
            $('#product').text(formatItem(data));
          })
          .fail(function (jqXHR, textStatus, err) {
            $('#product').text('Error: ' + err);
          });
    }
  </script>
</body>
</html>

There are several ways to get jQuery. In this example, I used the Microsoft Ajax CDN. You can also download it from http://jquery.com/, and the ASP.NET "Web API" project template includes jQuery as well.

Getting a List of Products

To get a list of products, send an HTTP GET request to "/api/products".

The jQuery getJSON function sends an AJAX request. For response contains array of JSON objects. The donefunction specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the product information.

$(document).ready(function () {
    // Send an AJAX request
    $.getJSON(apiUrl)
        .done(function (data) {
            // On success, 'data' contains a list of products.
            $.each(data, function (key, item) {
                // Add a list item for the product.
                $('<li>', { text: formatItem(item) }).appendTo($('#products'));
            });
        });
});

Getting a Product By ID

To get a product by ID, send an HTTP GET  request to "/api/products/id", where id is the product ID.

function find() {
    var id = $('#prodId').val();
    $.getJSON(apiUrl + '/' + id)
        .done(function (data) {
            $('#product').text(formatItem(data));
        })
        .fail(function (jqXHR, textStatus, err) {
            $('#product').text('Error: ' + err);
        });
}

We still call getJSON to send the AJAX request, but this time we put the ID in the request URI. The response from this request is a JSON representation of a single product.

Running the Application

Press F5 to start debugging the application. The web page should look like the following:

To get a product by ID, enter the ID and click Search:

If you enter an invalid ID, the server returns an HTTP error:

Reference

http://msdn.microsoft.com/en-us/library/hh833994(v=vs.108).aspx

comments powered by Disqus
User Profile
Rakesh Sinha
Team Lead
Delhi , INDIA
Email :You must Log In to access the contact details.
Latest Post from :rakesh
How to Calculate sum of a column in a dataset
View: 215 | Submitted on: 9/17/2014 6:48:19 AM
ASP.NET MVC 4 Interview Questions and Answers
View: 356 | Submitted on: 9/1/2014 10:10:25 PM
What New in ASP.NET MVC 5
View: 720 | Submitted on: 6/6/2014 12:52:30 AM
What is view state in .Net?
View: 907 | Submitted on: 4/21/2014 9:44:52 PM
Rename database in sql server
View: 338 | Submitted on: 2/6/2014 9:57:16 PM
Submit Articles | All Post of This User..

All rights reserved to dotnetcodes. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks.
Best viewed at 1024 x 768 resolution with Internet Explorer 5.0 or Mozila Firefox 3.5 or Google Crome and higher