Creating ASP.NET Web API And Consuming It Through HTML Clients - Part 2

Before reading this article, I would recommend reading the following previous part:

Consuming Web API through HTML clients

Today, we will be focusing on consuming web API through HTML clients. Trust me guys, it’s very easy to consume web API and we will do that using JQuery. If you are unfamiliar with JQuery then please refer W3Schools for getting some basic idea about it. Latest version of JQuery can be downloaded from here.

Modify the default file “index.cshtml” in the View/Home folder with the following Markup to provide a GUI for displaying products and their different actions.

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3.   
  4. <body>  
  5.     <header>  
  6.         <script type="text/javascript" src="../../Scripts/jquery-1.8.2.js"></script>  
  7.     </header>  
  8.     <div id="body">  
  9.         <section class="featured">  
  10.             <div class="content-wrapper">  
  11.                 <hgroup class="title">  
  12.                     <h1>Welcome to ASP.NET Web API | Demo by <a href="http://dipendrashekhawat.com" target="_blank">Dipendra Shekhawat</a></h1> </hgroup>  
  13.             </div>  
  14.         </section>  
  15.         <section class="content-wrapper main-content clear-fix">  
  16.             <div>  
  17.                 <h4>Product List</h4>  
  18.                 <input type="button" value="View All Products" onclick="GetAllProducts();" />  
  19.                 <ul id="ProductList" /> </div>  
  20.             <div>  
  21.                 <h4>Search by ID</h4>  
  22.                 <input type="text" id="searchProductID" size="5" />  
  23.                 <input type="button" value="Search" onclick="FindProduct();" />  
  24.                 <p id="prod" /> </div>  
  25.             <div>  
  26.                 <h4>Delete Product by ID</h4>  
  27.                 <input type="text" id="delProductID" size="5" />  
  28.                 <input type="button" value="Delete" onclick="DeleteProduct();" /> </div>  
  29.             <div>  
  30.                 <h4>Add Product </h4>  
  31.                 <table>  
  32.                     <tr>  
  33.                         <td>Name</td>  
  34.                         <td>  
  35.                             <input type="text" id="Name" />  
  36.                         </td>  
  37.                     </tr>  
  38.                     <tr>  
  39.                         <td>Type</td>  
  40.                         <td>  
  41.                             <input type="text" id="Type" />  
  42.                         </td>  
  43.                     </tr>  
  44.                     <tr>  
  45.                         <td>Description</td>  
  46.                         <td>  
  47.                             <input type="text" id="Description" />  
  48.                         </td>  
  49.                     </tr>  
  50.                     <tr>  
  51.                         <td>Price</td>  
  52.                         <td>  
  53.                             <input type="text" id="Price" />  
  54.                         </td>  
  55.                     </tr>  
  56.                     <tr>  
  57.                         <td colspan="3" align="center">  
  58.                             <input type="button" value="Add" onclick="AddProduct();" />  
  59.                         </td>  
  60.                     </tr>  
  61.                 </table>  
  62.             </div>  
  63.         </section>  
  64.     </div>  
  65. </body>  
output

Now add the following script tag just after the </body> (closing body tag) to call web API:
  1. <script type="text/javascript">  
  2.     var hostUrl = "http://" + document.location.hostname + ":" + window.location.port;  
  3.     var apiUrl = '/api/Product';  
  4.     $(document).ready(function() {});  
  5.   
  6.     function GetAllProducts()  
  7.     {  
  8.         $.ajax(  
  9.         {  
  10.             url: hostUrl + apiUrl,  
  11.             type: 'GET',  
  12.             dataType: 'json',  
  13.             success: function(data)  
  14.             {  
  15.                 DisplayProductList(data);  
  16.             },  
  17.             error: function()  
  18.             {  
  19.                 alert('Some error occured');  
  20.             }  
  21.         });  
  22.     }  
  23.   
  24.     function FindProduct()  
  25.     {  
  26.         var id = $('#searchProductID').val();  
  27.         $.getJSON(apiUrl + '/' + id).done(function(data)  
  28.         {  
  29.             DisplayProductForEdit(data);  
  30.         }).fail(function(jqXHR, textStatus, err)  
  31.         {  
  32.             $('#prod').text('Error: ' + err);  
  33.         });  
  34.     }  
  35.   
  36.     function DeleteProduct()  
  37.     {  
  38.         var id = $('#delProductID').val();  
  39.         $.ajax(  
  40.         {  
  41.             url: hostUrl + apiUrl + '/' + id,  
  42.             type: 'DELETE',  
  43.             dataType: 'json',  
  44.             success: function(data)  
  45.             {  
  46.                 alert('Product deleted');  
  47.                 GetAllProducts();  
  48.             },  
  49.             error: function()  
  50.             {  
  51.                 alert('Product not found');  
  52.             }  
  53.         });  
  54.     }  
  55.   
  56.     function UpdateProduct()  
  57.     {  
  58.         var product = {  
  59.             Id: $('#searchProductID').val(),  
  60.             Name: $('#EditName').val(),  
  61.             Type: $('#EditType').val(),  
  62.             Description: $('#EditDescription').val(),  
  63.             Price: $('#EditPrice').val()  
  64.         };  
  65.         $.ajax(  
  66.         {  
  67.             url: hostUrl + apiUrl,  
  68.             type: 'PUT',  
  69.             data: JSON.stringify(product),  
  70.             contentType: "application/json;charset=utf-8",  
  71.             success: function(data)  
  72.             {  
  73.                 alert('Employee updated');  
  74.                 GetAllEmployee();  
  75.             },  
  76.             error: function()  
  77.             {  
  78.                 alert('Some error occured');  
  79.             }  
  80.         });  
  81.     }  
  82.   
  83.     function AddProduct()  
  84.     {  
  85.         var product = {  
  86.             Name: $('#Name').val(),  
  87.             Type: $('#Type').val(),  
  88.             Description: $('#Description').val(),  
  89.             Price: $('#Price').val()  
  90.         };  
  91.         $.ajax(  
  92.         {  
  93.             url: hostUrl + apiUrl,  
  94.             type: 'POST',  
  95.             data: JSON.stringify(product),  
  96.             contentType: "application/json;charset=utf-8",  
  97.             success: function(data)  
  98.             {  
  99.                 alert('Product added');  
  100.                 GetAllProducts();  
  101.             },  
  102.             error: function()  
  103.             {  
  104.                 alert('Some error occured');  
  105.             }  
  106.         });  
  107.     }  
  108.   
  109.     function DisplayProductList(products)  
  110.     {  
  111.         $("#ProductList").empty();  
  112.         var result = "<table><th>ID</th><th>Name</th><th>Type</th><th>Description</th><th>Price</th>";  
  113.         $.each(products, function(index, product)  
  114.         {  
  115.             result += "<tr><td>" + product.Id + "</td><td> " + product.Name + "</td><td>" + product.Type + "</td><td>" + product.Description + "</td><td>" + '₹ ' + product.Price + "</td></tr>";  
  116.         });  
  117.         result += "</table>";  
  118.         $("#ProductList").html(result);  
  119.     }  
  120.   
  121.     function DisplayProductForEdit(product)  
  122.     {  
  123.         $("#prod").empty();  
  124.         if (product == null)  
  125.         {  
  126.             alert('Product Not Found')  
  127.             return;  
  128.         }  
  129.         $("#prod").empty();  
  130.         var result = "<table>" + "<tr><td>Name</td><td><input type='text' id='EditName' value='" + product.Name + "'</td></tr>" + "<tr><td>Type</td><td><input type='text' id='EditType' value='" + product.Type + "'</td></tr>" + "<tr><td>Description</td><td><input type='text' id='EditDescription' value='" + product.Description + "'</td></tr>" + "<tr><td>Price</td><td><input type='text' id='EditPrice' value='" + product.Price + "'</td></tr>" + "<tr><td colspan='3'align='center'><input type='button' value='Update' onclick='UpdateProduct();' </td></tr>" + "</table>";  
  131.         $("#prod").html(result);  
  132.     }  
  133. </script>  
The following are the screenshots for viewing all the products or finding a specific product. Similarly, you can delete a product from the list by specifying its ID or add a new product.
table

run

Hurrah! Now you have knowledge of creating ASP.NET Web API and consuming it through HTML Clients. Don’t keep it to yourself. Please feel free to share your knowledge among your friends or colleagues.