Nowadays there are broad range of clients like browsers, mobiles, iPhone and tablets using HTTP services. These HTTP services can be built by a Asp.net Web API framework…It contains MVC features like routing, controllers, action, results, filter but it is not a MVC Framework. It is a part of the core ASP.NET platform and can be used with MVC and other types of Web applications like ASP.NET Web Forms. It can also be used as a stand-alone Web services application
Introduction
In this article we will see the walk through of how to call the Web API with JavasScript and jQuery
Objective
In this context, we'll add an HTML page that uses AJAX to call the web API. We'll use jQuery to make the AJAX calls and also to update the page with the results.
Now lets create a UI by adding a HTML page right-click the project and select Add, then select New Item.
In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "index.html".
Add below HTML to the page
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Students Application</title>
</head>
<body>
<div>
<h2>Students</h2>
<ul id="Students" />
</div>
<div>
<h2>Search by Student ID</h2>
<input type="text" id="StutId" size="5" />
<input type="button" value="Search" onclick="find();" />
<p id="student" />
</div>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
var uri = 'api/Students';
$(document).ready(function () {
// Send an AJAX request
// Here to get a list of Students, we are sending an HTTP GET request to "/api/students".
$.getJSON(uri)
.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($('#Students'));
});
});
});
function formatItem(item) {
return item.Name + ': Marks'+" "+ item.Marks;
}
// To get a student by ID, send an HTTP GET request to "/api/Students/id", where id is the student ID.
function find() {
var id = $('#StutId').val();
$.getJSON(uri + '/' + id)
.done(function (data) {
$('#student').text(formatItem(data));
})
.fail(function (jqXHR, textStatus, err) {
$('#student').text('Error: ' + err);
});
}
</script>
</body>
</html>
getJSON
function sends an AJAX request. For response contains array of JSON objects. The done function specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the student information.
Now lets debug the Application and test