Getting Data Using Web API with ASP.NET MVC
Introduction
This article explains about how getting data or accessing data using web API with ASP.NET MVC step by step process.
Definition
Web API is an application programming interface (API). API is used to communicating or interacts with software components each other. ASP.NET Web API is a framework that makes it easy to build HTTP Service that reaches a broad range of clients, including browsers and mobile devices. Using ASP.NET web API can communicating with different devices from the same database.
Action Methods In Web API
In Web API we using default action methods. Get, Post, Put, Delete are four default action methods. When we add new Web API empty controller in our project, about mentioned actions methods are added default as well as some overloaded methods. Looks like below screen shots.
- Get: Used to access or get all data with the business logic wherever we want. Using 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 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 create simple Web API refer previous article link
Create Simple Web API with ASP.NET MVC
Then follow below steps.
Now create a new class in model 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 MVC controller not a Web API controller. Add a view page for display data using created Web API in Ajax table. Adding below code in the controller.
We are using ajax table for shows data. Add 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",
//contentType: 'application/json; charset=utf-8',
//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');
}
});
});
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. These ajax code add 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",
//contentType: 'application/json; charset=utf-8',
//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');
}
});
});
$("#GetData").click(function () {
var Id = prompt("Enter Customer Id");
$("#tblPopulation").show();
$.ajax({
url: 'http://localhost:53027/api/Demo',
dataType: "json",
type: "Get",
//contentType: 'application/json; charset=utf-8',
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(
{
//"searching": false,
"lengthMenu": [[5, 10, 50, 100, 150, -1], [5, 10, 50, 100, 150, "All"]]
});
//Apply the search
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 property are “URL”, “dataType”, “type”. We getting 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 mention 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 built our project and run web page and get output looks like below screen shots.
If need all customer details, click “Get All Data” button and get all data looks like below screen shot.
If need particular customer details click “Get Data” button give customer id and get specified data looks like below screen shot.
Conclusion
This article explains about how to get data using web API with ASP.NET MVC. I hope this very useful to students, fresher, and new developers.