Click here to Skip to main content
15,868,016 members
Articles / Web Development

AngularJS With MVC Web API (ASP.NET MVC RESTful Service)

Rate me:
Please Sign up or sign in to vote.
4.68/5 (64 votes)
6 Oct 2014CPOL6 min read 354.3K   16.2K   110   67
AngularJS integration with Web API explained with a product list and added new product with get and post method.

I. Introduction

In this article, I am going to explain how AngularJS works in the client side and how AngularJS can be integrated with Web API (ASP.NET MVC RESTFul Service) for CRUD operation. I have taken example of product list and add new product.

If we need to learn any new language, then what are all things that will come to mind:

  • How we can do the validation?
  • How we can execute the server side code and get the response back?
  • How HTML form data posts to the server side code to perform the database activities?
  • How to get the data from database, when page loads to display the data?
  • How to implement the session management?
  • How to implement security?

I hope when you will read the complete article, you will be able to understand how AngularJS works and you will have clarifications to some of the above questions. This blog will get you to start working on AngularJS with Web API.

II. What is AngularJS

AngularJS is a JavaScript framework. Using this, we can build rich and extensible web applications. This is completely built on HTML, Javascript and CSS, and will not having any other dependency to make it work.

Anugular is very close to MVC and MVVM but Angular has been declared as MVW pattern where "W" stand for "Whatever" (whatever works for you).

Basically, Angular has three components as shown below:

  • Template (View)
  • Scope (Model)
  • Controller

Image 1

Template(View): Template is the HTML part of the application. If you have to work with ASP.NET MVC, then it is same as cshtml or any other type of the view. In Angular JS, there will be no any server side view code. Beauty of this framework is without refresh of the complete page, we can inject the data to the view (add, modify and delete the HTML data without refreshing the page).

Scope(Model): Scope is the model object of the application at client side.

Controller: Controller is a function which actually contains the logical unit of the application. This will have two parameters, one is the controller name (this is empty scope object) and the other is array in this fields can be added. Controller will be exposed to the view.

III. Why AngularJS (Advantages of AngularJS)

  1. Angular does not depend on any server side technologies, this builds on pure HTML, Javascript and CSS.
  2. This is a very light weight application.
  3. This works on the SPA (Single Page Application) principle.
  4. AS in Angular components are separated, so the application can be highly testable. This support TDD development.
  5. Less development effort, in any project HTML developers are different and they develop HTML pages and provide to the development team, developer then converts all the HTML files to cshtml or ASPX or any other technologies and continues working. In this case, double effort is required for development and testing.

In AngularJS, development team can continue from the HTML page itself.

IV. AngularJS Components

  1. Module
  2. Directives
  3. Filters
  4. Expression

V. AngularJS with Server Side code(MVC Web API)

The worry for any developer is that if Angular works with only HTML, then how can server side code be executed. Angular facilitates much more flexibility on this, any server side code can be plucked through Ajax call. So in this case, separate component can be designed to invoke by Angular. API can be written in .NET, PHP, Java or any other technologies.

In this article, I am taking an example of Web API (ASP.NET MVC Web API).

Below is the architecture design for the server side code execution.

Image 2

Angular will have controller which will make an Ajax call to the web API and get the response back from the server after executing the code.

VI. Develop MVC Web API

Let’s start creating a new Web API with Visual Studio 2013.

Step 1

Open Visual Studio 2013->Select new project-->Web-->ASP.NET Web Application.

Image 3

Step 2

Select Web API:

Image 4

Step 3

Right click on controller folder and add new controller class file.

Image 5

Step 4

Select Controller and MVC 5 Controller with read/write action:

Image 6

Step 5

Rename the controller to “ProductController”.

Image 7

Step 6

API controller class will be like below:

Image 8

Step 7

In Web API, I have two functions, one to get the product list data and the other posts the product data from product add page of Angular and adds to the product list.

Step 7.1: GetAllProducts

This is the get RESTful service method and this will return all the product data.

Controller Constructor: This is just used to fill initial product data:

C#
public ProductController()
        {
            if (PgaeLoadFlag == 1) //use this only for first time page load
            {
                //Three product added to display the data
                products.Value.Add(new Product { ID = 1, Name = "bus", Category = "Toy", Price = 200.12M });
                products.Value.Add(new Product { ID = 2, Name = "Car", Category = "Toy", Price = 300 });
                products.Value.Add(new Product { ID = 3, Name = "robot", Category = "Toy", Price = 3000 });
                PgaeLoadFlag++;
            }
        }

This will give you result by running the URL “http://localhost:1110/api/product”.

C#
// GET api/product
       public List <product> GetAllProducts() //get method
       {
           //Instedd of static variable you can use database resource to get the data and return to API
           return products.Value; //return all the product list data
       }

The output of the method is as shown below:

Image 9

Step 7.2: ProductAdd

This is the post RESTful service method and this will save the product data which will post from Angular form or any other application. This method will receive the product data but in this blog I have taken for Angular page form.

C#
public void ProductAdd(Product product) //post method
       {
           product.ID = ProductID;
           products.Value.Add(product); //add the post product data to the product list
           ProductID++;
           //instead of adding product data to the static product list you can save data to the database.
       }

VII. Develop AngularJS Application and Integrate with Web API

1. Solution Structure

There are two projects in the solution structure, one for Web API and the other for Pure Angular application.

Image 10

2. Product List Page

In this page, I am getting the list of product data from web API and looping through the data to display in the page.

In the below snapshot, explain how module, controller, web API, model and data loop through integration.

Image 11

First run the “Product_Api”, then run the “Product_Web” application.

Run the URL to access the product list page http://localhost:3442/Productlist.html. Once you run this, it will execute the method “GetAllProducts”.

Image 12

After method executes and integrates with Angular page, this will display the page as below:

Image 13

3. Add new Product

In this page, I have an HTML form to enter new product details and the entered data post to the Web API post method.

Please have a close look at the below snapshot to understand how you can post the form data to the Web API method.

Image 14

First run the “Product_Api”, then run the “Product_Web” application.

Run the URL to access the product. Add new page http://localhost:3442/ProductAdd.html.

Image 15

Once user client clicks on submit, this will execute the Web API method “ProductAdd” by passing the product data and product data gets added in the product list.

Image 16

Now once rerun the product list page, you will find the “cycle” product in the product list.

Image 17

I have attached the complete source code; you can download it from the link at the top of the article and enjoy with Angular. :)

Note: For demo purposes, the script code is in the same page, when you design a real time application, then you can organize your module properly in a separate JS file.

Summary

I have explained about AngularJS and it components, and I have also explained how angular can be integrated with Web API.

Hope you have enjoyed reading this article. Please provide your votes, suggestions and feedback...to encourage me to write more articles.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Epicor Software
India India
16+ years of experience in designing and developing Microsoft technologies applications.
My expertise skills are ASP.Net,MVC 3/4,MVC 4 WEB API, C#, WCF, REST, UML, Design Pattern,Angular, Node, Type script and SQL server.

You can reach me @ mdafazal@gmail.com

Comments and Discussions

 
PraiseThank you so much Pin
Alice Nguyen30-Nov-18 17:55
professionalAlice Nguyen30-Nov-18 17:55 
QuestionThank You Pin
Member 136607025-Feb-18 9:48
Member 136607025-Feb-18 9:48 
QuestionHi Its was nice to see Code on Angular and API Pin
D.sivannarayana18-Dec-17 15:22
D.sivannarayana18-Dec-17 15:22 
QuestionNo explanation of merging of web api and angualar Pin
RonnyMahlangu4-Sep-17 21:44
RonnyMahlangu4-Sep-17 21:44 
QuestionThe add functionality doesn't work it gives me an ajax error Pin
Member 1336277215-Aug-17 18:40
Member 1336277215-Aug-17 18:40 
QuestionNot Work on any external api url Pin
Member 1199890420-Jun-17 0:13
Member 1199890420-Jun-17 0:13 
QuestionError Pin
Harmen Stoopendaal10-Jun-17 22:51
Harmen Stoopendaal10-Jun-17 22:51 
QuestionPlease provide full explanation, it is very unclear. Pin
Member 1130480029-May-17 0:48
Member 1130480029-May-17 0:48 
QuestionHow It Product_Web project created ? Pin
Member 1320783817-May-17 21:18
Member 1320783817-May-17 21:18 
QuestionGetting Error While Posting the data From Form Pin
Member 1048121823-Nov-16 4:39
professionalMember 1048121823-Nov-16 4:39 
SuggestionGood working example, wish the article was more descriptive of the process Pin
kannankeril20-Aug-16 15:55
kannankeril20-Aug-16 15:55 
I was hoping the article would walk me through the construction of the solution rather than dumping the completed solution in my hand. There does not seem to be a Views folder and a script file in the Models folder needs some explanation.

The organization of the projects and folders seem a bit confusing.

Questiongetting alert(error) Pin
sureshrk1-May-16 22:37
sureshrk1-May-16 22:37 
QuestionError Pin
Pravin Narkhede19-Jan-16 7:25
Pravin Narkhede19-Jan-16 7:25 
AnswerRe: Error Pin
AdyDeshmukh20-Mar-16 23:31
AdyDeshmukh20-Mar-16 23:31 
AnswerRe: Error Pin
Harmen Stoopendaal10-Jun-17 22:35
Harmen Stoopendaal10-Jun-17 22:35 
PraiseCongrats Pin
Member 840861217-Nov-15 8:26
Member 840861217-Nov-15 8:26 
QuestionCongrats Pin
Member 840861217-Nov-15 8:24
Member 840861217-Nov-15 8:24 
QuestionAdditions to this tutorial Pin
SirReed9919-Sep-15 9:59
SirReed9919-Sep-15 9:59 
QuestionAngularJS and Web API 3-tier Pin
Kyaw Soe Khaing3-Sep-15 23:22
Kyaw Soe Khaing3-Sep-15 23:22 
QuestionNot able to load http://localhost:1110/api/product Pin
Ashutosh Chaturvedi21-Jun-15 13:16
Ashutosh Chaturvedi21-Jun-15 13:16 
AnswerRe: Not able to load http://localhost:1110/api/product Pin
Afazal MD 310420921-Jun-15 17:14
professionalAfazal MD 310420921-Jun-15 17:14 
GeneralRe: Not able to load http://localhost:1110/api/product Pin
Ashutosh Chaturvedi21-Jun-15 18:18
Ashutosh Chaturvedi21-Jun-15 18:18 
GeneralRe: Not able to load http://localhost:1110/api/product Pin
Quintin Bressler2-Sep-15 2:20
Quintin Bressler2-Sep-15 2:20 
QuestionGetting Error Pin
Samumon18-Jun-15 1:57
Samumon18-Jun-15 1:57 
AnswerRe: Getting Error Pin
Paulo Henrique S.S.15-Jul-15 22:05
professionalPaulo Henrique S.S.15-Jul-15 22:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.