Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

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

0.00/5 (No votes)
6 Oct 2014 2  
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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here