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

A basic SPA application using AngularJS,WebAPI and Entity Framework

0.00/5 (No votes)
3 Mar 2014 1  
We will understand what is a single page application.We will see how to create a basic single page application using AngularJS ,WebAPI and Entity Framework

Download CRUD_using_AngualrJS_WebAPI_and_Entity_Framework-noexe.zip

Introduction

SPA which stands for Single Page Application is the latest trend in web application development.It is a web application that load a single HTML page initially and is dynamically updated as the user interacts with the application.

In this article we will see the requirement for SPAs and explore the technologies we can use to create a Single Page Application.We will also see how to create a basic application using AngularJS ,WebAPI and Entity Framework.

Background

The goal of a SPA is to provide the experience to the user which is like a desktop application. SPA provides rich User experience by reducing round trips to the server.This is achieved by moving as much logic as possible to the client.

In a Single Page Application or SPA the page never reloads though parts of the page may refresh. This reduces the round trips to the server to a minimum.

If we consider any web application there are two main components involved web server and web browser or the client.

Traditional web application

In a conventional Web application, every time the client calls the server, the server returns a new HTML page. This causes a page refresh in the browser. This would be familiar to anybody who has programmed in ASP.NET or any other server side framework. If a user needs to refresh the page for every small action on a web page it is not very user friendly.This was the normal scenario in traditional web applications as the client has limited computation resources earlier.But with the advances in computing and with multicore processors being a common thing on machines this workflow seems to under utilize the clients.

Also such web applications can be difficult to run in case of limited bandwidth.This is where Single Page Applications are useful.

SPA application

SPA also requests an initial web page from the server like a traditional web application. But after that first page loads, all interaction with the server happens asynchronously. Server side code is only run for retrieving and persisting application data and other resources.

Now let us understand the general architecture of a Single Page Application. Looking at the big picture first the application is structured as

SPA application

As is clear from the diagram the client side has lot more responsibilities in the case of SPAs than in a traditional web application. Implementing all these additional responsibilities using JavaScript and HTML
alone can increase the complexity and is also not an easy task to achieve and to maintain such a complex application.

Jquery drastically reduces the complexity in manipulating the DOM but still we need to understand the DOM architecture to manipulate it. Also testing code written using Javascript or Jquery can be a big challenge.

So building SPAs from a scratch can be real nightmare.This is where Javascript Presentation Frameworks are useful.There are Javascript open source frameworks available to create SPAs. Two of the most common ones are DurandalJS and AngularJS.

Most SPA applications are structured as:

The main components are

Model is the single source of data for the application.

View represents model to the end user.There is a change tracking system through which whenever the model changes all the dependent views are automatically updated.Similarly view change updates the bound model.There is a main shell page and views which are kind of mini pages which are loaded into the shell.

Controller ties views and model together.

Using the code

In this application we would be using the following frameworks and technologies

Client

Angularjs an open-source JavaScript framework by Google. It helps to structure browser-based applications using model,view and controller.

Server

WebAPI is a framework to build HTTP services and suitable for building RESTful services.

Entity Framework and SQL Server Entity Framework is an object-relational mapper that enables .NET developers to work with relational data using domain-specific objects. SQL server is the relational database most commonly used in .NET applications.

Here we would be using Angular to build a simple application that provides CRUD functionality so we would be looking into the main features of Angular. Angular is a complete SPA framework so it includes lot of different features not just about about Angular provides lots of features as a presentation framework some of which are:

  • Manages dependencies for us using Dependency Injection.
  • Declarative like HTML so it blends very nicely with HTML. It extends HTML rather than trying to manipulate it.
  • Includes native version of Jquery, Jqlite for DOM manipulation.
  • Two way data binding
  • Designed for testing

Creating the Client

AngularJS script

So lets get started building our first basic SPA using AngularJS. We will be discussing the features of AngularJS along the way .The first thing we need to do use AngularJS is to include the AngularJS library as

<script src="~/Scripts/js/angular.min.js"></script> 

Now we are ready to use the AngularJS features in our application.

Now we will create a module that will define the scope for the application and a controller that coordinates with the view and model. Though we are creating single module but a real world application can consist of multiple modules. Following is the module and the method to call the service get method.There are methods for other CRUD operations which are similar to the below get method.

var customersApp= angular.module('customersApp', ['ngGrid']);
 customersApp.controller('customerCtrl', function ($scope,userRepository) { })   

You might be wondering what the userRepository is.For that first we need to understand the concept of Services and Factories

Services and Factories

These are used to generate an object or function that represents the service which can be consumed by the rest of the application.

This object or function is then passed as a parameter to any other function which wants to use this service or factory.This is possible because of DI provided by angualrJS automatically.

When declaring serviceName as an injectable argument you will be provided with an instance of the function. In other words new Function(). So when using service as an argument a new instance of the service function is created.

When using factory as an argument the value of the argument is a value which is returned by invoking the function passed to factory method .Below illustration will make it more clear.

app.factory('MyFactory', function(){  
   return {      
   testfunction: function(text){   
          return "Hello"+text;    
          }    
   }          
});  

Here if we use MyFactory as a function argument then the value of that argument is the value returned by the function which is testfunction.Here we will be using the factory to fetch the data from the WebAPI.

customersApp.factory('customerRepository', function ($http) {
    return {
        getCustomers: function (callback) {
            $http.get(url).success(callback);
        }  

The $http service is an inbuilt Angular service that is used for communication with the remote HTTP servers.One of the most important services to understand is the $scope service.It acts as the glue between the controller and the view or the html template.

Controller is not aware what views are there in the application.It just knows about the scope ,which it sets and which is accessible from the view.If you have worked in MVVM or similar presentation pattern then it is similar to a viewmodel. Now lets go ahead and create our controller.

 customersApp.controller('customerCtrl', function ($scope, customerRepository) {
    getCustomers();
    function getCustomers() {
        customerRepository.getCustomers(function (results) {
            $scope.customerData = results;
        }) 
    }  

The get method fetches data from the WebAPI. The other methods for the CRUD operations are similar.

Now that we have the script ready we can create the view template.

View

Direcives are a way to extend the html.We can make custom HTML elements or extend the existing ones.So we can wrap the functionality that we want to provide in a directive.We can provide additional functionality without using directives also using Jquery so you think the advantage of directives.But the below example would make obvious the advantage of directives.

Using Jquery first we have to write

<input id="dateOfBirth"> 

and then call

$('#dateOfBirth').datepicker() 

Contrast this how we use could use the if datepicker is a directive

<input datepicker> 

So using directive is not only more convenient but also makes them part of our html.Directives can be either elements or attributes

ngBind The ngBind attribute tells Angular to replace the text content of the specified HTML element with the value of a given expression.We use the curly braces markup {{ }} or data binding expression usually which provides the same functionality.

ngModel binds the input element to a property on the scope set by the Controller

ng-app sets the scope for the angularjs application and can be placed on any element though typically placed on the root element.ng-app initializes angularjs app ,so this is a required directive in any application using angularjs

ng-controller attaches a controller to the view

The first directive we need to add to the page is <html ng-app="customersApp">

Above directive will instantiate the angularJS application.We will now specify the controller to use using the ng-controller directive .We will use the controller we had defined.

<body ng-controller="customerCtrl">

So the only thing we need to do in view is to use the $scope to access the data.As you might have felt this creates a decoupled architecture as the view and controller do not need to know about each other.

Now we can use the data binding expressions in our views to display the data. Data binding expression use the following form {{ name }} where name is the name of the variable we have added to the $scope.

Now that we have created the html template we can move to the WebAPI part to store and retrieve the data.

WebAPI

WebAPI is a framework for building HTTP services that cab be consumed by different types of clients such as browsers and mobile devices.It's an ideal platform to build RESTful services.We will be using WebAPI to perform CRUD operations on the database.Its quite simpleto perform CRUD operations using WebAPI.It provides methods that maps to standard HTTP verbs GET,POST ,PUT,DELETE.

These methods are used to perform database operations and handle the client requests.

First we will create the Customer entity which we need to perform the actions on using the WebAPI methods.

  public class Customer
    {
        public string id { get; set; }
        public string city { get; set; }
        public string name { get; set; }
        public string address { get; set; }
        public string contactNo { get; set; }
        public string emailId { get; set; }
    }
    public class CustomerContext : DbContext
    {
        public DbSet<Customer> Customers { get; set; }
    }  

Next we add the WebAPI controller class.

In the model option we will select our Customer class and we will have the actions generated for us.As we are using the Entity Framework so the data access code is handled by the Entity framework for us.Following are the CRUD operations using the Entity Framework.

  public class CustomerController : ApiController
    {
        // GET api/<controller>
        public IEnumerable<Customer> Get()
        {
            CustomerContext customersdb = new CustomerContext();
            return customersdb.Customers;
        }
       // POST api/<controller>
        public void Post([FromBody]Customer customer)
        {
            CustomerContext customersdb = new CustomerContext();
            customersdb.Customers.Add(customer);
            customersdb.SaveChanges();
        }
        // PUT api/<controller>/5
        public void Put(int id, [FromBody]Customer customer)
        {
            CustomerContext customersdb = new CustomerContext();
            Customer customerToRemove=customersdb.Customers.Find(customer.id);
            customersdb.Customers.Remove(customerToRemove);
            Customer updatedCustomer = customer;
            customersdb.Customers.Add(updatedCustomer);
            customersdb.SaveChanges();
        }
        // DELETE api/<controller>/5
          public void Delete(string id)
        {
            CustomerContext customersdb = new CustomerContext();
            Customer cust=customersdb.Customers.Find(id);
            customersdb.Customers.Remove(cust);
            customersdb.SaveChanges();
        } 
 
    } 

As we are using the code first approach so we will have the database structure created for us when we run the application.

We can insert a new customer as well as edit and delete the customers using the application.

Summary

So this was a basic introduction to the Single Page Applications.We saw how to create a CRUD application using AngularJS and WebAPI. Javascript frameworks like AngularJS can help us getting started creating a SPA application rapidly.

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