In this article I will explain with an example, how to call (consume) Web API 2 using AngularJS, AJAX and JSON in ASP.Net MVC Razor.
This article will explain how to make an AJAX POST call to Web API 2 Controller’s method using AngularJS, AJAX and JSON in ASP.Net MVC Razor.
What is Web API?
ASP.Net Web API is a framework to build HTTP services which can be consumed by cross platform clients including desktops or mobile devices irrespective of the Browsers or Operating Systems being used.
ASP.Net Web API supports RESTful applications and uses GET, PUT, POST, DELETE verbs for client communications.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Creating an Entity Data Model
Following is the Entity Data Model of the Customers Table of the Northwind Database which will be used later in this project.
Model
The CustomerModel class consists of the following property.
public class CustomerModel
{
///<summary>
/// Gets or sets Name.
///</summary>
public string Name { get; set; }
}
Web API Controller
In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller.
Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below.
Then give it a suitable name and click OK.
The next task is to register the Configuration for Web API in the Global.asax file so that the Web API is available for accessing on Web.
In order to do so open Global.asax file and add the following line.
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
Make sure you add it in the same order as shown below.
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
System.Web.Http.GlobalConfiguration.Configure(WebApiConfig.Register);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
}
The next step is to code the Web API Controller. The Web API Controller consists of a method named AjaxMethod which accepts an object of CustomerModel.
The records of the Customers are fetched using Entity Framework and are filtered using the StartsWith function based on the value of the Name property.
Finally the records are returned as Generic List Collection.
This method is decorated with Route attribute which defines its Route for calling the Web API method and HttpPost attribute which signifies that the method will accept Http Post requests.
public class AjaxAPIController : ApiController
{
[Route("api/AjaxAPI/AjaxMethod")]
[HttpPost]
public List<Customer> AjaxMethod(CustomerModel customer)
{
NorthwindEntities entities = new NorthwindEntities();
return (from c in entities.Customers.Take(10)
where c.ContactName.StartsWith(customer.Name)
select c).ToList();
}
}
Controller
Now you will need to add one empty Controller along with a View. The View will be used for calling the Web API 2 Controller’s method using jQuery AJAX.
The Controller consists of an empty Action method which simply returns the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
return View();
}
}
View
Next step is to add an Empty View without Model for the Controller.
The View consists of an HTML DIV to which ng-app and ng-controller AngularJS directives have been assigned.
The HTML DIV consists of an HTML TextBox, Button and Table which will be populated from JSON array using ng-repeat directive.
The Button has been assigned ng-click directive. When the Button is clicked, the Search function of the Controller gets called.
Inside the Search function, the $http service is used to make an AJAX call to the Web API 2 Controller’s method. The $http service has following properties and methods.
Properties
1. method – The method type of HTTP Request i.e. GET or POST.
2. url – URL of the Web API 2 Controller’s method.
3. dataType – The format of the data i.e. XML or JSON.
4. data – The parameters to be sent to the Web API 2 Controller’s method i.e. the Prefix TextBox value.
5. headers - List of headers to be specified for the HTTP Request.
Event Handler
1. success – This event handler is triggered once the AJAX call is successfully executed.
2. error – This event handler is triggered when the AJAX call encounters an error.
The response from the AJAX call is received in JSON format inside the Success event handler of the $http service. It is assigned to the Customers variable.
The ng-repeat directive as the name suggests repeats the element based on the length of the collection, in this scenario it will repeat the TR element (HTML Table Row).
The TBODY element of the HTML Table has been assigned ng-repeat directive in order to iterate through all the items of the Customers JSON array.
For each JSON object in the Customers JSON array, a TR element (HTML Table Row) is generated and appended into the HTML Table.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('MyApp', [])
app.controller('MyController', function ($scope, $http, $window) {
$scope.IsVisible = false;
$scope.Search = function () {
var customer = '{Name: "' + $scope.Prefix + '" }';
var post = $http({
method: "POST",
url: "/api/AjaxAPI/AjaxMethod",
dataType: 'json',
data: customer,
headers: { "Content-Type": "application/json" }
});
post.success(function (data, status) {
$scope.Customers = data;
$scope.IsVisible = true;
});
post.error(function (data, status) {
$window.alert(data.Message);
});
}
});
</script>
<div ng-app="MyApp" ng-controller="MyController">
Name:
<input type="text" ng-model="Prefix"/>
<input type="button" value="Submit" ng-click="Search()"/>
<hr/>
<table cellpadding="0" cellspacing="0" ng-show="IsVisible">
<tr>
<th>Customer Id</th>
<th>Name</th>
<th>Country</th>
</tr>
<tbody ng-repeat="m in Customers">
<tr>
<td>{{m.CustomerID}}</td>
<td>{{m.ContactName}}</td>
<td>{{m.Country}}</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
Screenshot
Downloads