+91-90427 10472
Dot net training in Chennai -Maria Academy

Consume Web api Http service in MVC solution

30 Oct 2016

Document by Vairavan – ganesanva@hotmail.com – + 919042710472

Create a MVC solution using Code First Approach MVC Entity framework.
Add a Web Api Controller Class as below,

Look on the WebApiConfig.cs how the Routes are made.

The API URL can be routed as both API/Controller/Id and Api/Controller/Action/Id by registering the Routes in Web api config.
Add the Below code in Api Controller(Used for CRUD),

private UsersContext db = new UsersContext();
// GET api/values
public IEnumerable<StudentDetails> GetallStudents()
return db.StudentDbset.ToList();
// GET api/values/5
public StudentDetails GetStudents(int id)
StudentDetails studentdetails = db.StudentDbset.Find(id);
return studentdetails;
// Post api/values/Delete/5
public string DeleteStudents(int id)
StudentDetails studentdetails = db.StudentDbset.Find(id);
return “Deleted”;
// POST api/values
public void Post([FromBody]string value)
// PUT api/values/5
public void Put(int id, [FromBody]string value)
// DELETE api/values/5
public void Delete(int id)

Screen clipping taken: 02-09-2016 18:44
The Above Api methods can be accessed using below URL,
The data can be returned as JSON,Xml or any other format depends on the attribute.

Create a new HTML page in the Solution as index.html

Put below code in Index.html,

<!DOCTYPE html>
<html xmlns=”http://www.w3.org/1999/xhtml”>
<title>Product App</title>
<h2>All Products</h2>
<ul id=”products” />
<h2>Search by ID</h2>
<input type=”text” id=”prodId” size=”5″ />
<input type=”button” value=”Search” onclick=”find();” />
<p id=”product” />
<script src=”http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js”></script>
var uri = ‘/api/values’;
$(document).ready(function () {
// Send an AJAX request
.done(function (data) {
// On success, ‘data’ contains a list of products.
$.each(data, function (key, item) {
// Add a list item for the product.
$(‘<li>’, { text: formatItem(item) }).appendTo($(‘#products’));
function formatItem(item) {
return item.studentName + ‘: $’ + item.Age;
function find() {
var id = $(‘#prodId’).val();
$.getJSON(uri + ‘/’ + id)
.done(function (data) {
.fail(function (jqXHR, textStatus, err) {
$(‘#product’).text(‘Error: ‘ + err);

Now the MVC Application Works with Controller web api repository and a HTML page.
The output will be,

Click below to download the solution,

Social tagging: > > > > > > > > > >