In this article I will explain with an example, how to use Web API with AngularJS and Entity Framework in ASP.Net MVC Razor.
An AngularJS client will be consume a Web API method which will perform Database operations using Entity Framework and the data returned from the Web API will be displayed in Grid format using AngularJS 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
The very first step is to create an ASP.Net MVC Application and connect it to the Northwind Database using Entity Framework. For more details please refer my article ASP.Net MVC: Simple Entity Framework Tutorial with example.
Following is the Entity Data Model of the Customers Table of the Northwind Database which will be used later in this project.
Using Web API with AngularJS and Entity Framework in ASP.Net MVC
 
 
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.
Using Web API with AngularJS and Entity Framework in ASP.Net MVC
 
Then give it a suitable name and click OK.
Using Web API with AngularJS and Entity Framework in ASP.Net MVC
 
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.
Note: If you want to learn more about these directives please refer my article Introduction to AngularJS.
 
The Button has been assigned ng-click directive. When the Button is clicked, the Search function of the Controller gets called.
Note: If you want to learn more about ng-click directive, please refer my article ng-click directive example.
 
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
Using Web API with AngularJS and Entity Framework in ASP.Net MVC
 
 
Downloads