Click here to Skip to main content
15,867,453 members
Articles / Programming Languages / Javascript

A basic SPA application using AngularJS,WebAPI and Entity Framework

Rate me:
Please Sign up or sign in to vote.
4.78/5 (28 votes)
3 Mar 2014CPOL9 min read 140.9K   8.9K   73   24
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.

Image 1

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

Image 2

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: Image 3

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.

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

C#
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.

JavaScript
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.Image 4

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.

JavaScript
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

JavaScript
<input id="dateOfBirth"> 

and then call

JavaScript
$('#dateOfBirth').datepicker() 

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

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

C#
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.

Image 5

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.

C#
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.

Image 6

Image 7

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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
I have a keen interest in technology and software development.I have worked in C#,ASP.NET WebForms,MVC,HTML5 and SQL Server.I try to keep myself updated and learn and implement new technologies.
Please vote if you like my article ,also I would appreciate your suggestions.For more please visit Code Compiled

Comments and Discussions

 
QuestionI am getting XMLHttpRequest error Pin
deepakkarma28-Sep-16 19:07
deepakkarma28-Sep-16 19:07 
GeneralMy vote of 4 Pin
agurrion18-Mar-16 16:10
agurrion18-Mar-16 16:10 
SuggestionToo bad for beginners Pin
cosmarvv18-Mar-16 6:25
cosmarvv18-Mar-16 6:25 
QuestionThis article ends abrutly Pin
bjnitti16-Nov-15 6:02
bjnitti16-Nov-15 6:02 
Questionquestion Pin
pshamsaie12-Jul-15 22:52
pshamsaie12-Jul-15 22:52 
QuestionDreadful Pin
Member 1035865718-Jul-14 11:12
Member 1035865718-Jul-14 11:12 
AnswerRe: Dreadful Pin
ashish__shukla30-Sep-14 7:25
ashish__shukla30-Sep-14 7:25 
GeneralMy vote of 5 Pin
Guruprasad.K.Basavaraju4-Jun-14 8:06
professionalGuruprasad.K.Basavaraju4-Jun-14 8:06 
QuestionAngular with Entity Framework Pin
Member 108006507-May-14 7:17
Member 108006507-May-14 7:17 
QuestionWeb Api self-host Pin
Lopezd5-May-14 5:21
Lopezd5-May-14 5:21 
AnswerRe: Web Api self-host Pin
ashish__shukla5-May-14 5:35
ashish__shukla5-May-14 5:35 
GeneralMy vote of 3 Pin
Member 1077312225-Apr-14 5:44
Member 1077312225-Apr-14 5:44 
QuestionChange to database first Pin
Member 1077312224-Apr-14 10:44
Member 1077312224-Apr-14 10:44 
AnswerRe: Change to database first Pin
Mycroft Holmes7-Nov-14 13:53
professionalMycroft Holmes7-Nov-14 13:53 
GeneralAngularjs CRUD Grid Pin
raju dasa11-Mar-14 0:11
raju dasa11-Mar-14 0:11 
GeneralRe: Angularjs CRUD Grid Pin
ashish__shukla20-Mar-14 3:10
ashish__shukla20-Mar-14 3:10 
QuestionHow the round trips will be reduced? Pin
hemantwithu4-Mar-14 23:18
hemantwithu4-Mar-14 23:18 
AnswerRe: How the round trips will be reduced? Pin
ashish__shukla5-Mar-14 0:51
ashish__shukla5-Mar-14 0:51 
GeneralRe: How the round trips will be reduced? Pin
hemantwithu5-Mar-14 23:52
hemantwithu5-Mar-14 23:52 
GeneralMy vote of 4 Pin
Manjunath Bilwar4-Mar-14 19:52
Manjunath Bilwar4-Mar-14 19:52 
QuestionExample doesn't run Pin
Antonino Porcino4-Mar-14 6:55
Antonino Porcino4-Mar-14 6:55 
AnswerRe: Example doesn't run Pin
ashish__shukla4-Mar-14 18:22
ashish__shukla4-Mar-14 18:22 
Hi,

As this is a visual studio 2012 project so apart from the normal references ,only Entity Framework 6.0 is required as the project is using the Code first to generate the database.Also you need to have SQL Server express installed on the machine.The required javascripts are already included in the project.
Please let me know if you are able to run the application now.
GeneralRe: Example doesn't run Pin
Antonino Porcino4-Mar-14 21:33
Antonino Porcino4-Mar-14 21:33 
GeneralRe: Example doesn't run Pin
Antonino Porcino5-Mar-14 1:15
Antonino Porcino5-Mar-14 1:15 

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.