Click here to Skip to main content
11,721,671 members (68,087 online)
Click here to Skip to main content

A basic SPA application using AngularJS,WebAPI and Entity Framework

, 3 Mar 2014 CPOL 73.7K 6.6K 65
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

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 CodeCompiled

You may also be interested in...

Comments and Discussions

 
Questionquestion Pin
pshamsaie12-Jul-15 22:52
memberpshamsaie12-Jul-15 22:52 
QuestionDreadful Pin
Member 1035865718-Jul-14 11:12
memberMember 1035865718-Jul-14 11:12 
AnswerRe: Dreadful Pin
Ashish__Shukla30-Sep-14 7:25
memberAshish__Shukla30-Sep-14 7:25 
GeneralMy vote of 5 Pin
Guruprasad.K.Basavaraju4-Jun-14 8:06
memberGuruprasad.K.Basavaraju4-Jun-14 8:06 
QuestionAngular with Entity Framework Pin
Member 108006507-May-14 7:17
memberMember 108006507-May-14 7:17 
QuestionWeb Api self-host Pin
Lopezd5-May-14 5:21
memberLopezd5-May-14 5:21 
AnswerRe: Web Api self-host Pin
Ashish__Shukla5-May-14 5:35
memberAshish__Shukla5-May-14 5:35 
GeneralMy vote of 3 Pin
Member 1077312225-Apr-14 5:44
memberMember 1077312225-Apr-14 5:44 
QuestionChange to database first Pin
Member 1077312224-Apr-14 10:44
memberMember 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
memberraju dasa11-Mar-14 0:11 
GeneralRe: Angularjs CRUD Grid Pin
Ashish__Shukla20-Mar-14 3:10
memberAshish__Shukla20-Mar-14 3:10 
QuestionHow the round trips will be reduced? Pin
hemantwithu4-Mar-14 23:18
memberhemantwithu4-Mar-14 23:18 
AnswerRe: How the round trips will be reduced? Pin
Ashish__Shukla5-Mar-14 0:51
memberAshish__Shukla5-Mar-14 0:51 
GeneralRe: How the round trips will be reduced? Pin
hemantwithu5-Mar-14 23:52
memberhemantwithu5-Mar-14 23:52 
GeneralMy vote of 4 Pin
Manjunath Bilwar4-Mar-14 19:52
memberManjunath Bilwar4-Mar-14 19:52 
QuestionExample doesn't run Pin
Antonino Porcino4-Mar-14 6:55
memberAntonino Porcino4-Mar-14 6:55 
AnswerRe: Example doesn't run Pin
Ashish__Shukla4-Mar-14 18:22
memberAshish__Shukla4-Mar-14 18:22 
GeneralRe: Example doesn't run Pin
Antonino Porcino4-Mar-14 21:33
memberAntonino Porcino4-Mar-14 21:33 
GeneralRe: Example doesn't run Pin
Antonino Porcino5-Mar-14 1:15
memberAntonino Porcino5-Mar-14 1:15 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150901.1 | Last Updated 3 Mar 2014
Article Copyright 2014 by ashish__shukla
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid