Click here to Skip to main content
13,346,708 members (23,354 online)
Click here to Skip to main content
Add your own
alternative version

Stats

259.9K views
15.1K downloads
111 bookmarked
Posted 6 Oct 2014

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

, 6 Oct 2014
Rate this:
Please Sign up or sign in to vote.
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

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.

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.

Step 2

Select Web API:

Step 3

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

Step 4

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

Step 5

Rename the controller to “ProductController”.

Step 6

API controller class will be like below:

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:

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”.

// 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:

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.

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.

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.

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”.

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

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.

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.

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.

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

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)

Share

About the Author

Afazal MD 3104209
Software Developer (Senior) Epicor Software
India India
10+ 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,AngularJS and SQL server.

You can reach me @ mdafazalp@gmail.com

You may also be interested in...

Pro

Comments and Discussions

 
QuestionHi Its was nice to see Code on Angular and API Pin
D.sivannarayana18-Dec-17 16:22
memberD.sivannarayana18-Dec-17 16:22 
QuestionNo explanation of merging of web api and angualar Pin
RonnyMahlangu4-Sep-17 22:44
memberRonnyMahlangu4-Sep-17 22:44 
QuestionThe add functionality doesn't work it gives me an ajax error Pin
Member 1336277215-Aug-17 19:40
memberMember 1336277215-Aug-17 19:40 
QuestionNot Work on any external api url Pin
Member 1199890420-Jun-17 1:13
memberMember 1199890420-Jun-17 1:13 
QuestionError Pin
Member 447822410-Jun-17 23:51
memberMember 447822410-Jun-17 23:51 
QuestionPlease provide full explanation, it is very unclear. Pin
Member 1130480029-May-17 1:48
memberMember 1130480029-May-17 1:48 
QuestionHow It Product_Web project created ? Pin
Member 1320783817-May-17 22:18
memberMember 1320783817-May-17 22:18 
QuestionGetting Error While Posting the data From Form Pin
Member 1048121823-Nov-16 5:39
professionalMember 1048121823-Nov-16 5:39 
SuggestionGood working example, wish the article was more descriptive of the process Pin
kannankeril20-Aug-16 16:55
memberkannankeril20-Aug-16 16:55 
Questiongetting alert(error) Pin
sureshrk1-May-16 23:37
membersureshrk1-May-16 23:37 
QuestionError Pin
Pravin Narkhede19-Jan-16 8:25
memberPravin Narkhede19-Jan-16 8:25 
AnswerRe: Error Pin
Member 1117284721-Mar-16 0:31
memberMember 1117284721-Mar-16 0:31 
AnswerRe: Error Pin
Member 447822410-Jun-17 23:35
memberMember 447822410-Jun-17 23:35 
PraiseCongrats Pin
Member 840861217-Nov-15 9:26
memberMember 840861217-Nov-15 9:26 
QuestionCongrats Pin
Member 840861217-Nov-15 9:24
memberMember 840861217-Nov-15 9:24 
QuestionAdditions to this tutorial Pin
SirReed9919-Sep-15 10:59
memberSirReed9919-Sep-15 10:59 
QuestionAngularJS and Web API 3-tier Pin
Kyaw Soe Khaing4-Sep-15 0:22
memberKyaw Soe Khaing4-Sep-15 0:22 
QuestionNot able to load http://localhost:1110/api/product Pin
Ashutosh Chaturvedi21-Jun-15 14:16
memberAshutosh Chaturvedi21-Jun-15 14:16 
AnswerRe: Not able to load http://localhost:1110/api/product Pin
Afazal MD 310420921-Jun-15 18:14
professionalAfazal MD 310420921-Jun-15 18:14 
GeneralRe: Not able to load http://localhost:1110/api/product Pin
Ashutosh Chaturvedi21-Jun-15 19:18
memberAshutosh Chaturvedi21-Jun-15 19:18 
GeneralRe: Not able to load http://localhost:1110/api/product Pin
Quintin Bressler2-Sep-15 3:20
memberQuintin Bressler2-Sep-15 3:20 
QuestionGetting Error Pin
Samumon18-Jun-15 2:57
memberSamumon18-Jun-15 2:57 
AnswerRe: Getting Error Pin
paulohss15-Jul-15 23:05
memberpaulohss15-Jul-15 23:05 
Questionno apicontroller Pin
Blue Clouds29-May-15 8:56
memberBlue Clouds29-May-15 8:56 
QuestionNo mention of security. Pin
tatran.eu@gmail.com24-May-15 12:44
membertatran.eu@gmail.com24-May-15 12:44 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.180111.1 | Last Updated 6 Oct 2014
Article Copyright 2014 by Afazal MD 3104209
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid