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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Net.Http;
- using System.Web.Http;
- using WebAPI.Models;
-
- namespace WebAPI.Controllers
- {
- public class DemoController : ApiController
- {
-
- public IEnumerable<Customer> Get()
- {
- return new List<Customer>
- {
- new Customer{Id=1,CustomerName="Arun",Address="9th Street",City="Erode",Pincode="637204"},
- new Customer{Id=2,CustomerName="Mohan",Address="Main Road",City="Namakkal",Pincode="637205"},
- new Customer{Id=3,CustomerName="Prapbu",Address="SKV Street",City="Salem",Pincode="637206"},
- new Customer{Id=4,CustomerName="Raja",Address="Raja Street",City="Chennai",Pincode="637207"},
- new Customer{Id=5,CustomerName="Ravi",Address="SMV Street",City="Covai",Pincode="637208"},
- new Customer{Id=6,CustomerName="Santhose",Address="SKM Street",City="Salem",Pincode="637209"},
- new Customer{Id=7,CustomerName="Mugesh",Address="Main Road",City="Trichy",Pincode="637846"},
- new Customer{Id=8,CustomerName="Mani",Address="Mani Street",City="Chennai",Pincode="637245"},
- new Customer{Id=9,CustomerName="Sankar",Address="Sankar Street",City="Tiruchengode",Pincode="637273"},
- new Customer{Id=10,CustomerName="Vignesh",Address="Main Road",City="Kondankattur",Pincode="637201"}
- };
- }
-
- public IEnumerable<Customer> Get(string Id)
- {
- int cusId= Convert.ToInt32(Id);
- return new List<Customer>
- {
- new Customer{Id=1,CustomerName="Arun",Address="9th Street",City="Erode",Pincode="637204"},
- new Customer{Id=2,CustomerName="Mohan",Address="Main Road",City="Namakkal",Pincode="637205"},
- new Customer{Id=3,CustomerName="Prapbu",Address="SKV Street",City="Salem",Pincode="637206"},
- new Customer{Id=4,CustomerName="Raja",Address="Raja Street",City="Chennai",Pincode="637207"},
- new Customer{Id=5,CustomerName="Ravi",Address="SMV Street",City="Covai",Pincode="637208"},
- new Customer{Id=6,CustomerName="Santhose",Address="SKM Street",City="Salem",Pincode="637209"},
- new Customer{Id=7,CustomerName="Mugesh",Address="Main Road",City="Trichy",Pincode="637846"},
- new Customer{Id=8,CustomerName="Mani",Address="Mani Street",City="Chennai",Pincode="637245"},
- new Customer{Id=9,CustomerName="Sankar",Address="Sankar Street",City="Tiruchengode",Pincode="637273"},
- new Customer{Id=10,CustomerName="Vignesh",Address="Main Road",City="Kondankattur",Pincode="637201"}
- }.Where(s=>s.Id==cusId);
- }
-
- }
- }
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.
- @{
- Layout = null;
- }
-
- <link href="//cdn.datatables.net/1.10.12/css/jquery.dataTables.min.css" rel="stylesheet" />
- <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
- <script src="//code.jquery.com/jquery-1.12.3.js"></script>
- <script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
- <h2>Welcome To Web API</h2>
- <input type="button" id="GetallData" value="Get All Data" />
- <input type="button" id="GetData" value="Get Data" /> <br />
-
- <table id="tblPopulation" style="display:none;">
- <thead>
- <tr>
- <td>Id</td>
- <td>Customer Name</td>
- <td>Address</td>
- <td>City</td>
- <td>Pincode</td>
- </tr>
- <tr>
- <td>
- <input type="text" />
- </td>
- <td>
- <input type="text" />
- </td>
- <td>
- <input type="text" />
- </td>
- <td>
- <input type="text" />
- </td>
- <td>
- <input type="text" />
- </td>
- </tr>
- </thead>
-
- </table>
-
-
- <script>
- $(document).ready(function () {
-
- $("#GetallData").click(function () {
- $("#tblPopulation").show();
- $.ajax({
-
- url: 'http://localhost:53027/api/Demo',
- dataType: "json",
- type: "Get",
-
-
- success: function (data) {
- var tr;
- console.log(data);
- for (var i = 0; i < data.length; i++) {
- tr = tr + "<tr>";
- tr = tr + "<td>" + data[i].Id + "</td>";
- tr = tr + "<td>" + data[i].CustomerName + "</td>";
- tr = tr + "<td>" + data[i].Address + "</td>";
- tr = tr + "<td>" + data[i].City + "</td>";
- tr = tr + "<td>" + data[i].Pincode + "</td>";
- tr = tr + "</tr>";
- }
- $('#tblPopulation').append(tr);
- tblFormate();
- },
- error: function (xhr) {
- alert('No Valid Data');
- }
- });
- });
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.
- <script>
- $(document).ready(function () {
-
- $("#GetallData").click(function () {
- $("#tblPopulation").show();
- $.ajax({
-
- url: 'http://localhost:53027/api/Demo',
- dataType: "json",
- type: "Get",
-
-
- success: function (data) {
- var tr;
- console.log(data);
- for (var i = 0; i < data.length; i++) {
- tr = tr + "<tr>";
- tr = tr + "<td>" + data[i].Id + "</td>";
- tr = tr + "<td>" + data[i].CustomerName + "</td>";
- tr = tr + "<td>" + data[i].Address + "</td>";
- tr = tr + "<td>" + data[i].City + "</td>";
- tr = tr + "<td>" + data[i].Pincode + "</td>";
- tr = tr + "</tr>";
- }
- $('#tblPopulation').append(tr);
- tblFormate();
- },
- error: function (xhr) {
- alert('No Valid Data');
- }
- });
- });
-
- $("#GetData").click(function () {
-
- var Id = prompt("Enter Customer Id");
- $("#tblPopulation").show();
- $.ajax({
-
- url: 'http://localhost:53027/api/Demo',
- dataType: "json",
- type: "Get",
-
- data: {Id:Id},
- success: function (data) {
- var tr;
- console.log(data);
- for (var i = 0; i < data.length; i++) {
- tr = tr + "<tr>";
- tr = tr + "<td>" + data[i].Id + "</td>";
- tr = tr + "<td>" + data[i].CustomerName + "</td>";
- tr = tr + "<td>" + data[i].Address + "</td>";
- tr = tr + "<td>" + data[i].City + "</td>";
- tr = tr + "<td>" + data[i].Pincode + "</td>";
- tr = tr + "</tr>";
- }
- $('#tblPopulation').append(tr);
- tblFormate();
- },
- error: function (xhr) {
- alert('No Valid Data');
- }
- });
- });
-
- function tblFormate() {
-
- var table = $('#tblPopulation').DataTable(
- {
-
- "lengthMenu": [[5, 10, 50, 100, 150, -1], [5, 10, 50, 100, 150, "All"]]
- });
-
- table.columns().eq(0).each(function (colIdx) {
- $('input', table.column(colIdx).header()).on('keyup change', function () {
- table
- .column(colIdx)
- .search(this.value)
- .draw();
- });
- });
- }
-
-
- });
- </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.