A Beginners Guide to work with ASP.NET Web API and AngularJS

Rajnilari2015
Posted by in AngularJS category on for Beginner level | Points: 250 | Views : 1318 red flag
Rating: 5 out of 5  
 2 vote(s)

WebAPI is a framework for building HTTP services that can be consumed by a wide range of clients like browsers, mobiles, desktop, tablets etc.AngularJS, on the otehr hand, is use for service consumption and presenting the data in the HTML templates. In this article we will look into the interaction between both these technologies with a step by step guideance.


 Download source code for A Beginners Guide to work with ASP.NET Web API and AngularJS

Recommendation
Read Read Json and display the records using AngularJS Expression before this article.

Introduction

WebAPI is a framework for building HTTP services that can be consumed by a wide range of clients like browsers, mobiles, desktop, tablets etc. AngularJS, on the other hand, is used for service consumption and presenting the data in the HTML templates. In this article we will look into the interaction between both these technologies with a step by step guidance.

Creating the WebAPI project

Fire up Visual Studio and then File -> New -> Project -> Web -> Asp.Net Web Application.

The next screen that pops up display's a list of templates and we need to choose Web API template.

Also set the authentication mode to No Authentication

Clicking on the OK button creates the Web API project whose structure is as under

Now expand the Controllers folder and we will find two files viz. HomeController.cs and ValuesController.cs

Expand the ValuesController.cs file and we will find that the sample WebAPI controller has been created for us

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace WebApplication3.Controllers
{
    public class ValuesController : ApiController
    {
        // GET api/values
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // GET api/values/5
        public string Get(int id)
        {
            return "value";
        }

        // 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)
        {
        }
    }
}

Run the application and click the API link in the browser to receive the below image

Now we can test the API Services of the ValuesController.cs through PostMan

Creating the Model

Here we will create our Employee model as under

public class Employee
{
    public int EmployeeID { get; set; }
    public string EmployeeName { get; set; }    
    public string EmailAdress { get; set; }
    public string PhoneNumber { get; set; }    
}

This is a simple Employee Class which has some scalar properties like EmployeeID,EmployeeName,EmailAdress,PhoneNumber.

Now let us create a WebAPI (say EmployeeController) as shown under

using System.Collections.Generic;
using System.Web.Http;

namespace WebAPI_AngularJs_Operation.Controllers
{
    [RoutePrefix("Employee")]
    public class EmployeeController : ApiController
    {
        // GET Employee/EmployeeData
        [Route("EmployeeRecords")]
        public List<Employee> Get()
        {
            return new List<Employee>()
            {
                new Employee { EmployeeID=1, EmployeeName="Niladri", EmailAdress="niladri@dnf.com", PhoneNumber="1111111111" }
                ,new Employee { EmployeeID=2, EmployeeName="Arina", EmailAdress="arina@dnf.com", PhoneNumber="2222222222" }
                ,new Employee { EmployeeID=3, EmployeeName="Rajlaxmi", EmailAdress="rajlaxmi@dnf.com", PhoneNumber="3333333333" }
                ,new Employee { EmployeeID=4, EmployeeName="RNA", EmailAdress="rna@dnf.com", PhoneNumber="4444444444" }

            };            
        }        
    }

    public class Employee
    {
        public int EmployeeID { get; set; }
        public string EmployeeName { get; set; }
        public string EmailAdress { get; set; }
        public string PhoneNumber { get; set; }
    }
}

Run the application and click the API link in the browser to receive the below image

Now we can test the API Services of the EmployeeController.cs through PostMan which reflects the below JSON

Consuming services through AngularJS

Now, it's time to consume the web services through AngularJS and to bind the data.

Step 1: Create an Application Module (employeeModule.js)

For this to happen, let us first create a employeeModule.js file whose content is as under

//creating an application module
var employeeAppModule = angular.module("employeeApp", []);

This js file basically creates an application module. Since AngularJS follows modular approach, so the modules are used to separate the logics like services, controllers, application etc. This on the other hand keep the code clean. Here we have declared an application employeeApp module using angular.module function.

Step 2: Create the Service file (employeeService.js)

As a next step we will create the service file (employeeService.js) as under

employeeAppModule.factory('EmployeeService', ['$http', function ($http) {

		var employeeService = {};
 
    	var urlBase = 'http://localhost:65436/Employee'; //the base for the Employee Resources
    	
    	//invoke the service
    	employeeService.getEmployees = function () {
        
        		return $http.get(urlBase + '/EmployeeRecords');
    	};
 
 	//returns the record obtained from the service
    return employeeService;
}]);

The factory method is use to create the service. It's syntax is

module.factory( 'factoryName', function );

In general, Services are JavaScript functions and are responsible to do a specific tasks. Services are normally injected using dependency injection mechanism of AngularJS (which we will look into the Controller part).

We have injected $http which is an inbuilt service used to make ajax call to get the server data.

We have create a function by the name getEmployees that uses the $http for fetching the server record that is assigned to the factory variable employeeService. Finally we return the employeeService object.

Step 3: Create the Controller file (employeeController.js)

Let us look into the employeeController.js

//The below code will fetch the data from EmployeeService and will pass to the $scope variable 

employeeAppModule.controller('EmployeeCtrl', function ($scope, EmployeeService) //injected the EmployeeService factory
{
 
    getEmployeeRecords(); //call the function
 
    function getEmployeeRecords() 
    {
        EmployeeService.getEmployees() //invoking the getEmployees() method of the EmployeeService factory

            .success(function (data) { // case when records found successfully

            	console.log(data); //just for display in the console

                $scope.employees = data;
 
            })

            .error(function (data, status) { // if something goes wrong

                console.error('failure loading the employee record', status, data);
                $scope.employees = { }; //return blank record if something goes wrong
 
            });
    }
});

The code pattern is a typical MVC one. First we have created the employeeAppModule.It is an Application Module that is use to initialize the application with controller which is EmployeeCtrl in our case.

Next we have created a controller module EmployeeCtrl and injected the EmployeeService into it using the Dependency Injection pattern of AngularJS.

For reading data from the Web API, we are invoking the getEmployees() method of the EmployeeService where in the success case we are setting the data to the $scope.employees variable and if anything goes wrong while reading the data, we are setting the $scope.employees = { } as empty.

The $scope.employees variable acts as a glue for carrying the data from the controller to the view (i.e. html part).

Step 4: Create the View (index.html)

Now comes the binding part.If we observe, we have mutilpe employee records. This reminds us to perform a looping in the Json data which can be done using ng-repeat.

Let us now look into the code

<!DOCTYPE html>
<html>
<head>
  <script data-require="angular.js@1.4.0-beta.6" data-semver="1.4.0-beta.6" src="https://code.angularjs.org/1.4.0-beta.6/angular.js">
  </script> 
  <script src="employeeModule.js"></script>
 <script src="employeeController.js"></script>
 <script src="employeeService.js"></script>

</head>

<body ng-app="employeeApp">
		<div align="center"><b><u><font size="8px">Employee Records</font></u></b></div>
		<div ng-controller="EmployeeCtrl" align="center">  
			<table border="1">
				<tr bgcolor="gray">
					  
					  <td>Employee ID</td>	
					  <td>Employee Name</td>
					  <td>Email</td>
					  <td>Phone Number</td>					  
				</tr>
				<tr ng-repeat="employee in employees">
					  <td><span>{{employee.EmployeeID}}</span></td>	
					  <td><span>{{employee.EmployeeName}}</span></td>						  
					  <td><span>{{employee.EmailAdress}}</span></td>	
					  <td><span>{{employee.PhoneNumber}}</span></td>
				</tr>				
			</table>
		</div>		
	</body>
</html>

Step 5: Run the application

Finally we can run the application. But we encounter the below problem

The message

XMLHttpRequest cannot load http://localhost:65436/Employee/EmployeeRecords. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

indicates that we need to Enable Cross-Origin Requests in ASP.NET Web API

So for this let's go back to the WebAPI project and from the Nu-get package manager issue

Install-Package Microsoft.AspNet.WebApi.Cors

Once done, then open WebApiConfig.cs file and enable the CORS as under

The complete code is as under

using System.Web.Http;
using System.Web.Http.Cors;

namespace WebAPI_AngularJs_Operation
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services    
            config.EnableCors();
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}

Now run the application again and the final output is as under

Since AngularJS supports the concepts of "Separation of Concerns" using services architecture, so we have created the AngularJS application by creating seperate JavaScript files.However, it can be done in a single JavaScript file (employeeController_AllInOne.js) as shown below

// Step 1: Creating an application module
var employeeAppModule = angular.module("employeeApp", []);

//Step 2: Create the Controller
//The below code will fetch the data from EmployeeService and will pass to the $scope variable 

employeeAppModule.controller('EmployeeCtrl', function ($scope, EmployeeService) //injected the EmployeeService factory
{
 
    getEmployeeRecords(); //call the function
 
    function getEmployeeRecords() 
    {
        EmployeeService.getEmployees() //invoking the getEmployees() method of the EmployeeService factory

            .success(function (data) { // case when records found successfully

            	console.log(data); //just for display in the console

                $scope.employees = data;
 
            })

            .error(function (data, status) { // if something goes wrong

                console.error('failure loading the employee record', status, data);
                $scope.employees = { }; //return blank record if something goes wrong
 
            });
    }
});

//Step 3: Create the Service using Factory
employeeAppModule.factory('EmployeeService', ['$http', function ($http) {

		var employeeService = {};
 
    	var urlBase = 'http://localhost:65436/Employee'; //the base for the Employee Resources
    	
    	//invoke the service
    	employeeService.getEmployees = function () {
        
        		return $http.get(urlBase + '/EmployeeRecords');
    	};
 
 	//returns the record obtained from the service
    return employeeService;
}]);

References

AngularJS How to Tips & Tricks at Techfunda

AngularJS Developer Guide

Conclusion

Let us summarize what we have learnt in this article

  1. Creation of a WebAPI project
  2. Expose the WebAPI services
  3. Invoking the WebAPI's through Postman and viewing the result in JSON format
  4. Create an Application Module of AngularJS
  5. Create the Service for WebAPI consumption using the Factory Method
  6. Controller creation
  7. Discussed the concept of Dependency Injection and how to use the same
  8. Data binding and looping concept using ng-repeat
  9. Resolved the problem of CORS
  10. An end to end interaction between AngularJS and WebAPI and creation of AngularJS project by satisfying the concepts of "Separation of Concerns"

Hope the article will help as a guidance to the newbies wants to start with AngularJS and WebAPI. Thanks for reading. Zipped file attached.

Page copy protected against web site content infringement by Copyscape

About the Author

Rajnilari2015
Full Name: Niladri Biswas (RNA Team)
Member Level: Platinum
Member Status: Member,MVP
Member Since: 3/17/2015 2:41:06 AM
Country: India
-- Thanks & Regards, RNA Team


Login to vote for this post.

Comments or Responses

Posted by: Sheonarayan on: 6/22/2016 | Points: 25
Thanks Niladri, very detailed and step by step article. An article on managing accounts (Token based authentication & authorization) using WebAPI would be a wonderful article in this series.

Regards

Posted by: A2H on: 6/25/2016 | Points: 25
Good Article Niladri.
Posted by: Rajnilari2015 on: 6/26/2016 | Points: 25
Thanks.
Posted by: Mailtodhanz on: 7/8/2016 | Points: 25
Nice article....
Posted by: Bhuvanesh6 on: 7/21/2016 | Points: 25
Nice Article Niladri.

Login to post response

Comment using Facebook(Author doesn't get notification)