Click here to Skip to main content
Click here to Skip to main content

Creating Single Page Application using Hot Towel Template

, 20 Feb 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
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). 

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. 

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. 

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

Add the connection string information into web.config file.   

    <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 

    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 

    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.

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. 

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)

Share

About the Author

Arthanarieaswaran
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

 
SuggestionGood Article, but will need to improve on writing skills PinmemberPRASHANTANU26-May-14 4:47 
GeneralRe: Good Article, but will need to improve on writing skills PinmemberArthanarieaswaran26-May-14 16:43 
QuestionMissing References Pinmemberajvad22-May-14 7:00 
AnswerRe: Missing References Pinmemberajvad22-May-14 7:08 
GeneralRe: Missing References Pinmemberajvad22-May-14 7:52 
GeneralRe: Missing References PinmemberArthanarieaswaran26-May-14 16:41 
QuestionGoogle analytics or Adsense... PinmemberGuilherme Morais30-Mar-14 11:56 
AnswerRe: Google analytics or Adsense... PinmemberArthanarieaswaran15-Apr-14 18:02 
AnswerRe: Google analytics or Adsense... PinmemberGuilherme Morais16-May-14 10:48 
GeneralRe: Google analytics or Adsense... PinmemberArthanarieaswaran18-May-14 16:26 
GeneralMy vote of 5 PinprofessionalRenju Vinod19-Mar-14 20:39 
GeneralRe: My vote of 5 PinmemberArthanarieaswaran19-Mar-14 20:53 
Questiondoubt reg. breeze controller PinmemberMember 106531318-Mar-14 0:23 
AnswerRe: doubt reg. breeze controller PinmemberArthanarieaswaran10-Mar-14 17:27 
GeneralRe: doubt reg. breeze controller PinmemberMember 1065313111-Mar-14 4:37 
Questiondoubt reg. breeze contrller PinmemberMember 106531318-Mar-14 0:23 

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
Web01 | 2.8.150327.1 | Last Updated 20 Feb 2014
Article Copyright 2014 by Arthanarieaswaran
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid