Calling the ASP.Net Web API With jQuery and JavaScript

Introduction

In this article, we will use jQuery and JavaScript for calling the Web API. We know that the ASP. Net Web API is a framework for creating Web APIs of the .NET Framework. In this article, we will use the ASP. Net Web API to create a Web API that returns a list of items.

Now we will provide the procedure for creating the Web API.

Step 1

First we create the Web API project as in the following:

  • Open Visual Studio 2012 and select "File" -> "New" -> "Project...".
  • In the Template Window select Visual C# >Web and then select "ASP. Net MVC 4 Web Application". Change the name of this to "ExampleAPI" and click on the "OK" button.
example.jpg

In the New ASP. Net MVC 4 project window select "Web API" and click the "OK" button.

exampl1.jpg

Step 2

Now we Add a Model

In the ASP. Net Web API the Model can be serialized automatically in Java Script Object Notation (JSON) and Extensible Markup Language (XML) format. We can use the model to represent the data  in our application.
Now we will describe how to create the model in the application.

  • In the Solution Explorer right-click on the "Model" folder
  • From the context menu select "Add" and select the class
ex1.jpg

Step 3

We change the class name to "Item" and add this code to the class:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. namespace ExampleAPI.Models  
  6. {  
  7.     public class Item  
  8.     {  
  9.         public int Id { getset; }  
  10.         public string name { getset; }  
  11.         public string Type { getset; }  
  12.         public decimal cost { getset; }  
  13.     }  
  14. }

Step 4

Add the Controller

The Controller handles the HTTP requests. There are two types of controllers; they are:

HomeController: used for serving the HTML pages to the WebSite. It cannot have direct interaction with the Web API.
ValuesController: works as an example of the Web API.

Use the following to add the controller:

  • In the Solution Explorer right-click on the "Controller" folder.
  • Select "Add and Select Controller".
  • Change the name of the controller to "Items".
  • In the Template select "Empty API Controller".
example 3.jpg


cont.jpg

Now add the following code to the Controller.

  1. namespace ExampleAPI.Controllers  
  2. {  
  3.     using System;  
  4.     using System.Collections.Generic;  
  5.     using System.Linq;  
  6.     using System.Net;  
  7.     using System.Net.Http;  
  8.     using System.Web.Http;  
  9.     using ExampleAPI.Models;  
  10.     public class ItemsController : ApiController  
  11.     {  
  12.         Item[] items = new Item[]  
  13.         {  
  14.             new Item{Id = 1,name="Apple", Type="Fruit",cost=100},  
  15.             new Item{Id = 2,name="Tomato",Type="vasitable",cost=50},  
  16.             new Item {Id = 3,name="T-Shirt",Type="cloths",cost=500}  
  17.         };  
  18.         public IEnumerable<Item> GetAllItems()  
  19.         {  
  20.             return items;  
  21.         }  
  22.         public Item GetItemById(int id)  
  23.         {  
  24.             var item = items.FirstOrDefault((I) => I.Id == id);  
  25.             if (item == null)  
  26.             {  
  27.                 throw new HttpResponseException(HttpStatusCode.NotFound);  
  28.             }  
  29.             return item;  
  30.         }  
  31.         public IEnumerable<Item>GetItemsByType(string type)  
  32.         {  
  33.             return items.Where(  
  34.                 (I) => string.Equals(I.Type, type,  
  35.                     StringComparison.OrdinalIgnoreCase));  
  36.         }  
  37.     }  
  38. } 

Step 5

For calling the Web API with jQuery an JavaScript

In the Solution Explorer, expand the Home Folder and double-click on the Index.cshtml.

cshtml.jpg

And write this code.

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <title>ASP.NET Web API</title>  
  5.     <link href="../../Content/Site.css" rel="stylesheet" />  
  6.     <script src="../../Scripts/jquery-1.7.1.min.js"  
  7.         type="text/javascript"></script>  
  8.         <script type="text/javascript">  
  9.             $(document).ready(function ()  
  10.             {  
  11.                  $.getJSON("api/items/",  
  12.                 function (Data) {  
  13.                     $.each(Data, function (key, val)  
  14.                 {  
  15.                     var str = val.name + ': $' + val.cost;  
  16.                         $('<li/>', { text: str })  
  17.                         .appendTo($('#items'));  
  18.                     });  
  19.                 });  
  20.             });  
  21.             function show() {  
  22.                 var Id = $('#itId').val();  
  23.                 $.getJSON("api/items/" + Id,  
  24.                     function (Data) {  
  25.                         var str = Data.name + ': $' + Data.cost;  
  26.                         $('#items').text(str);  
  27.                     })  
  28.                 .fail(  
  29.                     function (jqXHR, textStatus, err) {  
  30.                         $('#items').text('Error: ' + err);  
  31.                     });  
  32.             }  
  33.         </script>  
  34. </head>  
  35. <body id="body" >  
  36.     <div class="main-content">  
  37.         <div>  
  38.             <h1>Showing All Items </h1>  
  39.             <ul id="items"/>  
  40.         </div>  
  41.         <div>  
  42.             <label for="itId">ID:</label>  
  43.             <input type="text" id="itId" size="5"/>  
  44.             <input type="button" value="Search" onclick="show();" />  
  45.             <p id="item" />  
  46.         </div>  
  47.     </div>  
  48. </body>  
  49. </html> 

Result

 resultex.jpg

 Search the Item Through Id

resultex2.jpg


Similar Articles