Getting Data Using Web API With ASP.NET MVC

Introduction

This article explains about getting data or accessing data using web API with ASP.NET MVC. Before reading this article, kindly read the previous part of this article.

Definition

Web API (Application Programming Interface) is used for helping the software components with each other. ASP.NET Web API is a framework that makes it easy to build HTTP Services that reach a broad range of clients, including browsers and mobile devices. Using ASP.NET, web API can communicate with different devices from the same database.

Action Methods In Web API

In Web API, we use default action methods. Get, Post, Put, and Delete are four default action methods. When we add new Web API empty controller in our project, the above mentioned action methods are added by default along with some overloaded methods. Look at the below screenshots.

  • Get
    Used to access or get all data with the business logic wherever we want. We use overload method (Get (int id)), to access or get specified data help of any one unique values as an argument with the business logic wherever we want.

  • Post
    Used to save or store the data in the database with the business logic from wherever we can do.

  • Put
    Used to modified or update the data.

  • Delete
    Used to delete the data.

Steps for Getting Data Using WEP API

Step 1

For creating simple Web APIs, refer to the previous article's link.

Then, follow the below steps.

Now, create a new class in Models folder and add properties for our requirement. Here, we are going to create customer details.

Step 2

Create a list variable for Customer class and assign data into the list in “Demo” controller. Write the following code in the controller. 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Net.Http;  
  6. using System.Web.Http;  
  7. using WebAPI.Models;  
  8.   
  9. namespace WebAPI.Controllers  
  10. {  
  11.     public class DemoController : ApiController  
  12.     {  
  13.           
  14.         public IEnumerable<Customer> Get()  
  15.         {  
  16.             return new List<Customer>  
  17.             {  
  18.                 new Customer{Id=1,CustomerName="Arun",Address="9th Street",City="Erode",Pincode="637204"},  
  19.                 new Customer{Id=2,CustomerName="Mohan",Address="Main Road",City="Namakkal",Pincode="637205"},  
  20.                 new Customer{Id=3,CustomerName="Prapbu",Address="SKV Street",City="Salem",Pincode="637206"},  
  21.                 new Customer{Id=4,CustomerName="Raja",Address="Raja Street",City="Chennai",Pincode="637207"},  
  22.                 new Customer{Id=5,CustomerName="Ravi",Address="SMV Street",City="Covai",Pincode="637208"},  
  23.                 new Customer{Id=6,CustomerName="Santhose",Address="SKM Street",City="Salem",Pincode="637209"},  
  24.                 new Customer{Id=7,CustomerName="Mugesh",Address="Main Road",City="Trichy",Pincode="637846"},  
  25.                 new Customer{Id=8,CustomerName="Mani",Address="Mani Street",City="Chennai",Pincode="637245"},  
  26.                 new Customer{Id=9,CustomerName="Sankar",Address="Sankar Street",City="Tiruchengode",Pincode="637273"},  
  27.                 new Customer{Id=10,CustomerName="Vignesh",Address="Main Road",City="Kondankattur",Pincode="637201"}  
  28.             };  
  29.         }  
  30.   
  31.     public IEnumerable<Customer> Get(string Id)  
  32.         {  
  33.             int cusId= Convert.ToInt32(Id);  
  34.             return new List<Customer>  
  35.             {  
  36.                 new Customer{Id=1,CustomerName="Arun",Address="9th Street",City="Erode",Pincode="637204"},  
  37.                 new Customer{Id=2,CustomerName="Mohan",Address="Main Road",City="Namakkal",Pincode="637205"},  
  38.                 new Customer{Id=3,CustomerName="Prapbu",Address="SKV Street",City="Salem",Pincode="637206"},  
  39.                 new Customer{Id=4,CustomerName="Raja",Address="Raja Street",City="Chennai",Pincode="637207"},  
  40.                 new Customer{Id=5,CustomerName="Ravi",Address="SMV Street",City="Covai",Pincode="637208"},  
  41.                 new Customer{Id=6,CustomerName="Santhose",Address="SKM Street",City="Salem",Pincode="637209"},  
  42.                 new Customer{Id=7,CustomerName="Mugesh",Address="Main Road",City="Trichy",Pincode="637846"},  
  43.                 new Customer{Id=8,CustomerName="Mani",Address="Mani Street",City="Chennai",Pincode="637245"},  
  44.                 new Customer{Id=9,CustomerName="Sankar",Address="Sankar Street",City="Tiruchengode",Pincode="637273"},  
  45.                 new Customer{Id=10,CustomerName="Vignesh",Address="Main Road",City="Kondankattur",Pincode="637201"}  
  46.             }.Where(s=>s.Id==cusId);  
  47.         }  
  48.   
  49.     }  
  50. }   

Step 3

Now build web API and run following URL format “localhost:portNumber/api/Api_controll_Name” we can see the XML output. For in our project run following URL http://localhost:53027/Api/Demo/ looks like below.

Step 4

Go to the home controller and add an action method for Add View. This controller is an MVC controller, not a Web API controller. Add a View page for displaying the data using created Web API, in AJAX table. Add the below code in the controller.

We are using Ajax table for showing data. Add the following code in the view page. 

  1. @{  
  2.     Layout = null;  
  3. }  
  4.   
  5. <link href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />  
  6. <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>  
  7. <script src="//code.jquery.com/jquery-1.12.3.js"></script>  
  8. <script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>  
  9. <h2>Welcome To Web API</h2>  
  10. <input type="button" id="GetallData" value="Get All Data" />  
  11. <input type="button" id="GetData" value="Get Data" /> <br />  
  12.   
  13. <table id="tblPopulation" style="display:none;">  
  14.     <thead>  
  15.         <tr>  
  16.             <td>Id</td>  
  17.             <td>Customer Name</td>  
  18.             <td>Address</td>  
  19.             <td>City</td>  
  20.             <td>Pincode</td>  
  21.         </tr>  
  22.         <tr>  
  23.             <td>  
  24.                 <input type="text" />  
  25.             </td>  
  26.             <td>  
  27.                 <input type="text" />  
  28.             </td>  
  29.             <td>  
  30.                 <input type="text" />  
  31.             </td>  
  32.             <td>  
  33.                 <input type="text" />  
  34.             </td>  
  35.             <td>  
  36.                 <input type="text" />  
  37.             </td>  
  38.         </tr>  
  39.     </thead>  
  40.   
  41. </table>  
  42.   
  43.       
  44.     <script>  
  45.         $(document).ready(function () {  
  46.   
  47.             $("#GetallData").click(function () {  
  48.                 $("#tblPopulation").show();  
  49.                 $.ajax({  
  50.   
  51.                     url: 'http://localhost:53027/api/Demo',  
  52.                     dataType: "json",  
  53.                     type: "Get",  
  54.                     //contentType: 'application/json; charset=utf-8',  
  55.                     //data: {Id:Id},  
  56.                     success: function (data) {  
  57.                         var tr;  
  58.                         console.log(data);  
  59.                         for (var i = 0; i < data.length; i++) {  
  60.                             tr = tr + "<tr>";  
  61.                             tr = tr + "<td>" + data[i].Id + "</td>";  
  62.                             tr = tr + "<td>" + data[i].CustomerName + "</td>";  
  63.                             tr = tr + "<td>" + data[i].Address + "</td>";  
  64.                             tr = tr + "<td>" + data[i].City + "</td>";  
  65.                             tr = tr + "<td>" + data[i].Pincode + "</td>";  
  66.                             tr = tr + "</tr>";  
  67.                         }  
  68.                         $('#tblPopulation').append(tr);  
  69.                         tblFormate();  
  70.                     },  
  71.                     error: function (xhr) {  
  72.                         alert('No Valid Data');  
  73.                     }  
  74.                 });  
  75.             });   

Step 5

We are going to call our web API using Ajax. We are writing Ajax code inside the button click event. We created two buttons, one for getting all data (Get All Data), another one for getting specified data (Get Data) based on customer id. Add  the Ajax code in the same view page. Add below ajax code. 

  1. <script>  
  2.         $(document).ready(function () {  
  3.   
  4.             $("#GetallData").click(function () {  
  5.                 $("#tblPopulation").show();  
  6.                 $.ajax({  
  7.   
  8.                     url: 'http://localhost:53027/api/Demo',  
  9.                     dataType: "json",  
  10.                     type: "Get",  
  11.                     //contentType: 'application/json; charset=utf-8',  
  12.                     //data: {Id:Id},  
  13.                     success: function (data) {  
  14.                         var tr;  
  15.                         console.log(data);  
  16.                         for (var i = 0; i < data.length; i++) {  
  17.                             tr = tr + "<tr>";  
  18.                             tr = tr + "<td>" + data[i].Id + "</td>";  
  19.                             tr = tr + "<td>" + data[i].CustomerName + "</td>";  
  20.                             tr = tr + "<td>" + data[i].Address + "</td>";  
  21.                             tr = tr + "<td>" + data[i].City + "</td>";  
  22.                             tr = tr + "<td>" + data[i].Pincode + "</td>";  
  23.                             tr = tr + "</tr>";  
  24.                         }  
  25.                         $('#tblPopulation').append(tr);  
  26.                         tblFormate();  
  27.                     },  
  28.                     error: function (xhr) {  
  29.                         alert('No Valid Data');  
  30.                     }  
  31.                 });  
  32.             });  
  33.   
  34.             $("#GetData").click(function () {  
  35.                  
  36.                 var Id = prompt("Enter Customer Id");  
  37.                 $("#tblPopulation").show();  
  38.                 $.ajax({  
  39.   
  40.                     url: 'http://localhost:53027/api/Demo',  
  41.                     dataType: "json",  
  42.                     type: "Get",  
  43.                     //contentType: 'application/json; charset=utf-8',  
  44.                     data: {Id:Id},  
  45.                     success: function (data) {  
  46.                         var tr;  
  47.                         console.log(data);  
  48.                         for (var i = 0; i < data.length; i++) {  
  49.                             tr = tr + "<tr>";  
  50.                             tr = tr + "<td>" + data[i].Id + "</td>";  
  51.                             tr = tr + "<td>" + data[i].CustomerName + "</td>";  
  52.                             tr = tr + "<td>" + data[i].Address + "</td>";  
  53.                             tr = tr + "<td>" + data[i].City + "</td>";  
  54.                             tr = tr + "<td>" + data[i].Pincode + "</td>";  
  55.                             tr = tr + "</tr>";  
  56.                         }  
  57.                         $('#tblPopulation').append(tr);  
  58.                         tblFormate();  
  59.                     },  
  60.                     error: function (xhr) {  
  61.                         alert('No Valid Data');  
  62.                     }  
  63.                 });  
  64.             });  
  65.   
  66.                 function tblFormate() {  
  67.   
  68.                     var table = $('#tblPopulation').DataTable(  
  69.                      {  
  70.                          //"searching": false,  
  71.                          "lengthMenu": [[5, 10, 50, 100, 150, -1], [5, 10, 50, 100, 150, "All"]]  
  72.                      });  
  73.                     //Apply the search  
  74.                     table.columns().eq(0).each(function (colIdx) {  
  75.                         $('input', table.column(colIdx).header()).on('keyup change'function () {  
  76.                             table  
  77.                                 .column(colIdx)  
  78.                                 .search(this.value)  
  79.                                 .draw();  
  80.                         });  
  81.                     });  
  82.                 }  
  83.   
  84.               
  85.         });  
  86.     </script>   

Explanation

In Ajax we are using very important properties which are “URL”, “dataType”, “type”. We get or access our data using “URL;” we are calling our web API from where we hosted. Our API URL is “http://localhost:53027/Api/Demo/”. Another property is dataType, it is mentioned as a return type of data format like JSON. The final one is “type”, it is used to mention which type of methods like Get, Post, Put and Delete.

Step 6

Finally build our project and run web page and get the output  which looks like below screen shots.


If you need all customer details, click “Get All Data” button and get all data, which  looks like the below screen shot.


If you need particular customer details click “Get Data” button, give customer id, and get specified data which looks like the below screen shot.



Conclusion

This article explained how to get the data using web API with ASP.NET MVC. I hope this proves useful to students, freshers, and new developers.

Up Next
    Ebook Download
    View all
    Learn
    View all