Google+

Sunday, November 23, 2014

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4

In this article we describe Step by Step How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4.  We'll use Visual Studio 2012 templates and scaffolding in order to create a fully functional SPA web application in just 10 minutes. Later, you could adapt this SPA application to your necessities. The server side will be a Web API using REST , while the client side will be a SPA app . Our SPA web page will look like this:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4


From time now, everything has been moving undoubtedly from desktop applications to the Web World Apps. However, nowadays web applications are facing several problems like bad user experience due to web page re-rendering, poor performance because of page reloads and constant re-transmission of data on user interactions, and lack of offline support (meaning that no server connection implies no client alive).

Single-page applications (SPA), or single-page interfaces (SPI), are web applications built on a single one web page, with the intention of provide the user with a desktop application experience, replicating a desktop environment in the web browser. That means that all SPA code is rendered in a single web page load, and can be run on different devices like smartphones, tablets and of course desktops.  SPAs are written in JavaScript , do not require page reloading, and use specialized frameworks like AngularJS, Knockout and more.

Some examples of SPAs are Google Maps, Gmail,  iCloud, GitHub, Google Drive, Hotmail, and Soundcloud . The term "SPA" was first used by Steve Yen in 2005, but the first known experiments on SPA Apps are the 2002 Stuart Morris self-contained website at  slashdotslash   (works only on IE6)  ,  and the US patent by Lucas Birdeau, Kevin Hakman, Michael Peachey and Evan Yeh , describing a single page application implementation. 

SPA apps have therefore several important features like:

1) SPA apps respond like native applications : with minimal response time gained by moving data and processing from the server to the client, and moving business logic to the client : this way, only data validation and permanent storage are located on server side.

2) SPA's bandwidth is minimal : communication with the server Ajax's done , usually in very small JSON  requests. 

3) SPA render like desktop applications :  essentially without server round-trips to retrieve HTML.

4) SPAs are accessible applications : users can use SPAs from smartphones, tablets, laptops etc.

5) SPAs can keep working offline : a SPA can go offline if the server connection falls, and  synchronize the local data with the server afterwards. 

6) No need to download updates : all users need to do is to reload the browser to load the latest version.

7) Navigation between "different" pages is smooth : no page reloading is necessary, since new pages are generated on the fly, without calling the server.

8) SPAs are cross-platform: a SPA works on any operating system . 


Asp.Net  MVC4 comes with the Knockout.js framework, built upon the MVVM two-way data binding software pattern,  which goal is to isolate the UI from the business logic, making the data flow between a ViewModel and Binder in the middle, to synchronize data between the changes made on the View and the Model layer. The ViewModel code replaces the Controller, and makes automatically that synchronization, without knowing neither which View is being exposed, nor where is the data coming from.  

Schematically, MVVM can be put this way:
View: holds the user interface UI with declarative bindings

ViewModel: is a representation of the data, more a Model than a View, holds unsaved data,  and handles the application/presentation logic : as for MSDN, the ViewModel 
"decouples the View from the Model, and consolidates the business logic into the ViewModel and the Model where it can be tested"(MSDN)
The difference between presentation and business logic is, Business logic manages data, while presentation logic manages users behavior. 

Model: data validation business logic:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 1

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 2





Build Single Page Applications (SPA) for mobile and tablets using MVC 4


First, open Visual Studio 2012 and create a new Asp.Net MVC 4 Web Application project :

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 3


Next, choose the "Single Page Application" option :

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 4



After creation, take a look at the new folders & files added to the project:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 5



As you can see, several important files have been added: a CSS stylesheet , 2 Controllers, some .js script files, and most important, the Knockout.js framework.
As for the data Model, the files added are C# classes representing the entities that we'll be using:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 6



The "ToDo" entity has only two properties , besides the ID index : "Title" and "IsDone" :

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 7




It also has a foreign key which represents the Many-To-One relationship between a "Todo" object and the "TodoList" to which the object belongs. That means, every Todo object can belong to one and only one TodoList, and every TodoList can have one or many Todo objects in it.









The TodoList have just two properties, besides the ID index : the "UserID" which represents the user who owns the List, and the list "Title":

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 8



Also, the TodoList has a generic List<> containing all Todo objects belonging to it.

The Data Context holds the Todo and the TodoList objects in the correspondent generic DbSet<> :

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 9
The DbContext is connected with a SqlServer DataBase , stored at the "D through the "DefaultConnection" connection string , in the web.config :


How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 10


The Sql database will be placed inside the App_Data folder (the "|DataDirectory|" in the web.config):

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 11

The two Controllers are Web APIs which exposes all CRUD (Create Retrieve Update Delete) functionality , and will be called  via Ajax requests while using our SPA app:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 12



The CRUD functionality is applied through the different HTTP VERBS ("GET" = read a record , "POST" = create  a new item, "PUT" = update some item , "DELETE" = delete an item).

The client side will be a SPA app, build according to the MVVM architecture, meaning it will have a View, a Model and a ViewModel.

The View is the following:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 13

It just have some HTML5 tags like section and articles, and every article has a header with the Title, and an <ul> data bound to the "todos" objects.
The data bind is made using the Knockout framework:


How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 14



The ViewModel uses directly the Knockout framework to synchronize the data changes between View and Model, at client side:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 MVVM


How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 15



The following are the javascript files which our SPA app is using:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 16


All code was just automatically added to the project via templates, without any intervention from us. So just build and run it:


How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 17



First, the user is required to log in, in order to load the TodoLists that she/he owns:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 18


Then, the user just adds Todo lists or appends new Todo items to an existent list:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 19




How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 20




How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 21




The items can be added, deleted or updated.
After the user is done and logs out, she/he can log in again, and see all lists preserved on database.
All the CRUD functionality is hold in a SINGLE web page, and the server is called only in case there is the need of preserving data on disk. This makes a SPA web application.
You can set some breakpoints on the Web API, and debug (F5) the application, to see the Ajax requests in action:

How to Build Single Page Applications (SPA) for mobile and tablets using MVC 4 22


Next, you can modify this SPA application, changing the Model, to fit your needs.

In this article we learned Step by Step How to Build a Single Page Application (SPA) for mobile and tablets using MVC 4. 
Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן


No comments:

Post a Comment