Click here to Skip to main content
15,884,388 members
Articles / Web Development / ASP.NET
Article

Creating Single Page Application using Hot Towel Template

Rate me:
Please Sign up or sign in to vote.
4.85/5 (15 votes)
20 Feb 2014CPOL5 min read 60.9K   1.9K   33   23
This article explains creating Single Page Application using Hot Towel Template.

Introduction

Single-Page Applications (SPAs) are Rich, Responsive Web apps that load a single HTML page and dynamically update that page as the user interacts with the app.

This code sample gives the demo application for creating Single Page Application using Hot Towel SPA Template (Knockout, Durandal, Breeze). 

Image 1

This application will be useful for understanding the basics of Single Page Application in some extend. If you follow and create the application your own, it will give great experience on SPA. 

Background

Please take a look into the Durandal, Knockout and Breeze basics for more understands the below steps.

Durandal 

Durandal is small JavaScript framework designed to make building Single Page Applications (SPAs) simple and elegant.  

Knockout 

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model. 

Breeze 

Breeze is a JavaScript library that helps you manage data in rich client applications. It store & retrieve the data in database, execute queries etc. 

Hot Towel Template 

Hot Towel creates a great starting point for building a Single Page Application (SPA) with ASP.NET. It provides a modular structure for your code, view navigation, data binding, rich data management and simple but elegant styling.  

Open Data Protocol 

The purpose of the Open Data protocol (OData) is to provide a REST-based protocol for CRUD-style operations (Create, Read, Update and Delete) against resources exposed as data services. 

Pre-requisites    

To run this sample in development machine, machine should have Visual Studio 2012 or higher and MVC 4 with  Hot Towel Template. If reader has some basic knowledge on MVVM pattern it helps to understand better Hot Towel SPA. 

Description 

This code sample describes step by step creation of My Contact project using MVC 4 - Hot Towel Single Page Application Template.

I am explaining the step by step creation of My Contact project using MVC 4 Hot Towel SPA and I have written inline comment in the source code for better understanding the code. In this web page I am concentrating on steps for creating this application. 

Step 1: Create My Contacts project using MVC 4 -> Hot Towel SPA. 

Image 2

Image 3

Step 2: Create database & table.

Create database under App_Data folder, please see the below image for database creation.  

App_Data -> Add -> New Items -> SQL Server Compact 4.0 Local Database.  

It can be any database, but corresponding connection string has to mention in the web.config file.

I am taking SQL Server Compact 4.0 Local Database. 

Image 4

Double click the MyContact.sdf file and create table with column Id, Name, Mobile, Email, see the below image.

Image 5

Add the connection string information into web.config file.   

ASP.NET
  <connectionStrings>
  <add name="MyContactDB" connectionString="Data Source=|DataDirectory|MyContact.sdf" providerName="System.Data.SqlServerCe.4.0" />
</connectionStrings>

Step 3: Create Model and DataContext Classes

Contact model class, Contact.cs and datacontext class MyContactDbcontext.cs under Models folder

Contact.cs 

C#
public class Contact
{
    public int Id { get; set; }
    [Required, MaxLength(100)]
    public string Name { get; set; }
    [Required]
    [RegularExpression(@"\(?\d{3}\)?-? *\d{3}-? *-?\d{4}",
        ErrorMessage = "Invalid mobile")]
    public string Mobile { get; set; }

    [RegularExpression(
    @"^\w+[\w-\.]*\@\w+((-\w+)|(\w*))\.[a-z]{2,3}$",
        ErrorMessage = "Invalid email")]
    public string Email { get; set; }
}

MyContactDbContext.cs 

C#
public class MyContactDBContext : DbContext
{
    //WebConfig-Connection string name has to mention here for connecting the database.
    public MyContactDBContext()
        : base(nameOrConnectionString: "MyContactDB")
    {

    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
        Database.SetInitializer<MyContactDBContext>(null);

    }

    public DbSet<Contact> Contacts { get; set; }

}

Step 4: Web API class for Breeze framework contact with database. BreezeController.cs (ApiController) under Controller folder.

Image 6

BreezeController.cs 

    [BreezeController]
    public class BreezeController : ApiController
    {
 
        readonly EFContextProvider<MyContactDBContext> _contextProvider =
            new EFContextProvider<MyContactDBContext>();
 
        [HttpGet]
        public string Metadata()
        {
            //assemblyref://System.Web.Http.OData
            //OData reference has to add for Breeze connection with database for getting metadata.           
            //This reference will not come with this template - it can be download from online,
            //also this code sample package is having this assembly dll.
            return _contextProvider.Metadata();
        }
 
        [HttpGet]
        public IQueryable<Contact> Contacts()
        {
            return _contextProvider.Context.Contacts;
 
        }
 
        [HttpPost]
        public SaveResult SaveChanges(JObject saveBundle)
        {
            return _contextProvider.SaveChanges(saveBundle);
 
       } 
 
} 

System.web.Http.OData - reference has to add for getting Metadata using Breeze 

Until now we created database and web API for breeze communicate with database. Before going into next session, please take a look into the Durandal, Knockout and Breeze basics. 

Client Side Code 

Hot Towel SPA client side code constructed using MVVM pattern, client html/java script file will act Model, View & ViewModel classes. Let us see client side code in the below section.

All client side code comes under App folder in the My Contact project. It has three folders 

services (model) -> contains java script files for model, datacontext, log and Breeze.partial-entities.

viewmodels -> contains java script files it act as viewmodel classes for html view files

view-> contains html files mostly view (UI) files. 

From here I am start mentioning the file name, it has to copy from the downloaded source code. Source code has inline comment whenever if necessary. 

Step 5: Bootstrapper and Configuration files

main.js files works like bootstrapper and config.js (it has to create or copy from source code) contain configuration information like remoteServicName

Step 6: Create file in services folder (copy files from source code) - MODEL 

model.js file helps to sync up table column using Breeze Metadata file. 

breeze.partial-entities.js into App->services folder, some reason template is not creating this file or I was missing something on this. But this is the way to work around.  

datacontext.js file is getting data, add/updating using Breeze API controller, Breeze framework will take care all the service calls. 

Step 7: Create html files under view folder (copy files from source code) - VIEW

contacts.html -> list all available contacts extracted from the database, knockout framework helps for data-binding from viewmodel to view. 

Similarly contactadd.html & contactedit.html are used for add and edit respectively. 

Step 8: Create java script files under viewmodel folder  (copy files from source code) - VIEWMODEL

Usually viewmodel file contains properties, methods and command which can be invoke by the view. 

Note: naming convention of both view & viewmodel should be same, and then durandal understands view & its corresponding viewmodel files.

contacts.js -> contacts properties contains list of contacts and some other properties/command for searching by name.

contactadd.js/contactedit.js - doing add/edit properties and commands. For understanding purpose add/edit files are created two separate views, also it helps to navigate independently each other. 

Step 9: Updating routes for navigating Contacts, Contact Add views. 

shell.js (App->viewmodels), below code has to update for display Contacts, Add item in the menu list. 

Image 7

Step 10: Build & Run 

Once done all the above steps, add the required namespaces in all .cs files and Build & Run the application. It will redirect to contacts list page. Click 'Add' menu, then add some contact information and click 'Save'. Then you can able to see the newly added record in contacts view. 

Conclusion

I hope this article helps to understands MVC 4 Hot Towel SPA and able to create your own My Contact project. Please let me your valuable comments, suggestions and quires on this article. Thanks to John Papa for Hot Towel template. 

You can use Fiddler Web Debugger tool for analyzing OData request from Breeze framework.  

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
India India
Artha is a Technical Lead in Windows Phone, WPF [MVVM, PRISM], ASP.NET [MVC 3.0 & 4.0], C#.NET, VB.NET and ASP.

Windows Phone

Microsoft Developer Network


Published Tools in Visual Studio Galleries


Published Source Codes in CodePlex


Microsoft Virtual Academy Profile


Published Articles in Code Project


Microsoft Certified Professional Developer (MCPD) Microsoft ASP.NET Developer 3.5 (070-564, 070-536, 070-562, 070 315)

Comments and Discussions

 
QuestionError load new references Pin
Z@clarco25-Jan-16 22:45
Z@clarco25-Jan-16 22:45 
QuestionFooter- From where "About Arthanarieaswaran" coming .? Pin
laxmeesh.joshi9-Jun-15 2:58
laxmeesh.joshi9-Jun-15 2:58 
AnswerRe: Footer- From where "About Arthanarieaswaran" coming .? Pin
laxmeesh.joshi9-Jun-15 3:24
laxmeesh.joshi9-Jun-15 3:24 
GeneralRe: Footer- From where "About Arthanarieaswaran" coming .? Pin
Arthanarieaswaran Shanmugaraj9-Jun-15 3:55
Arthanarieaswaran Shanmugaraj9-Jun-15 3:55 
SuggestionGood Article, but will need to improve on writing skills Pin
PRASHANTANU26-May-14 3:47
PRASHANTANU26-May-14 3:47 
GeneralRe: Good Article, but will need to improve on writing skills Pin
Arthanarieaswaran Shanmugaraj26-May-14 15:43
Arthanarieaswaran Shanmugaraj26-May-14 15:43 
GeneralRe: Good Article, but will need to improve on writing skills Pin
laxmeesh.joshi9-Jun-15 0:57
laxmeesh.joshi9-Jun-15 0:57 
GeneralRe: Good Article, but will need to improve on writing skills Pin
laxmeesh.joshi9-Jun-15 3:25
laxmeesh.joshi9-Jun-15 3:25 
GeneralRe: Good Article, but will need to improve on writing skills Pin
Arthanarieaswaran Shanmugaraj9-Jun-15 3:51
Arthanarieaswaran Shanmugaraj9-Jun-15 3:51 
QuestionMissing References Pin
ajvad22-May-14 6:00
ajvad22-May-14 6:00 
AnswerRe: Missing References Pin
ajvad22-May-14 6:08
ajvad22-May-14 6:08 
GeneralRe: Missing References Pin
ajvad22-May-14 6:52
ajvad22-May-14 6:52 
GeneralRe: Missing References Pin
Arthanarieaswaran Shanmugaraj26-May-14 15:41
Arthanarieaswaran Shanmugaraj26-May-14 15:41 
QuestionGoogle analytics or Adsense... Pin
Guilherme Morais30-Mar-14 10:56
Guilherme Morais30-Mar-14 10:56 
AnswerRe: Google analytics or Adsense... Pin
Arthanarieaswaran Shanmugaraj15-Apr-14 17:02
Arthanarieaswaran Shanmugaraj15-Apr-14 17:02 
AnswerRe: Google analytics or Adsense... Pin
Guilherme Morais16-May-14 9:48
Guilherme Morais16-May-14 9:48 
GeneralRe: Google analytics or Adsense... Pin
Arthanarieaswaran Shanmugaraj18-May-14 15:26
Arthanarieaswaran Shanmugaraj18-May-14 15:26 
GeneralMy vote of 5 Pin
Renju Vinod19-Mar-14 19:39
professionalRenju Vinod19-Mar-14 19:39 
GeneralRe: My vote of 5 Pin
Arthanarieaswaran Shanmugaraj19-Mar-14 19:53
Arthanarieaswaran Shanmugaraj19-Mar-14 19:53 
Questiondoubt reg. breeze controller Pin
Member 106531317-Mar-14 23:23
Member 106531317-Mar-14 23:23 
AnswerRe: doubt reg. breeze controller Pin
Arthanarieaswaran Shanmugaraj10-Mar-14 16:27
Arthanarieaswaran Shanmugaraj10-Mar-14 16:27 
GeneralRe: doubt reg. breeze controller Pin
Member 1065313111-Mar-14 3:37
Member 1065313111-Mar-14 3:37 
Questiondoubt reg. breeze contrller Pin
Member 106531317-Mar-14 23:23
Member 106531317-Mar-14 23:23 

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.