Coder Social home page Coder Social logo

hottowel's Introduction

Hot Towel SPA Template


Hot Towel: Because you don't want to go to the SPA without one!

Want to build a SPA but can't decide where to start? Use Hot Towel and in seconds you'll have a SPA and all the tools you need to build on it!

Hot Towel creates a great starting point for building a Single Page Application (SPA) with ASP.NET. Out of the box you it provides a modular structure for your code, view navigation, data binding, rich data management and simple but elegant styling. Hot Towel provides everything you need to build a SPA, so you can focus on your app, not the plumbing.

Learn more about building a SPA from John Papa's videos, tutorials and Pluralsight courses.

Application Structure

Hot Towel SPA provides an App folder which contains the JavaScript and HTML files that define your application.

Inside the App folder:

The App folder contains a collection of modules. These modules encapsulate functionality and declare dependencies on other modules. The views folder contains the HTML for your application and the viewmodels folder contains the presentation logic for the views (a common MVVM pattern). The services folder is ideal for housing any common services that your application may need such as HTTP data retrieval or local storage interaction. It is common for multiple viewmodels to re-use code from the service modules.

ASP.NET MVC Server Side Application Structure

Hot Towel builds on the familiar and powerful ASP.NET MVC structure.

  • App_Start
  • Content
  • Controllers
  • Models
  • Scripts
  • Views

Featured Libraries

Installing via the Visual Studio 2012 Hot Towel SPA Template

Hot Towel can be installed as a Visual Studio 2012 template. Just click File | New Project and choose ASP.NET MVC 4 Web Application. Then select the 'Hot Towel Single Page Application" template and run!

Installing via the NuGet Package

Hot Towel is also a NuGet package that augments an existing empty ASP.NET MVC project. Just install using Nuget and then run!

Install-Package HotTowel

How Do I Build On Hot Towel?

Simply start adding code!

  1. Add your own server-side code, preferably Entity Framework and WebAPI (which really shine with Breeze.js)
  2. Add views to the App/views folder
  3. Add viewmodels to the App/viewmodels folder
  4. Add HTML and Knockout data bindings to your new views
  5. Update the navigation routes in shell.js

Walkthrough of the HTML/JavaScript

Views/HotTowel/index.cshtml

index.cshtml is the starting route and view for the MVC application. It contains all the standard meta tags, css links, and JavaScript references you would expect. The body contains a single <div> which is where all of the content (your views) will be placed when they are requested. The @Scripts.Render uses Require.js to run the entrance point for the application's code, which is contained in the main.js file. A splash screen is provided to demonstrate how to create a splash screen while your app loads.

<body>
    <div id="applicationHost">
        @Html.Partial("_splash")
    </div>

    @Scripts.Render("~/scripts/vendor")
        <script type="text/javascript" src="~/App/durandal/amd/require.js" 
			data-main="@Url.Content("~/App/main")"></script>
</body>

App/main.js

The main.js file contains the code that will run as soon as your app is loaded. This is where you want to define your navigation routes, set your start up views, and perform any setup/bootstrapping such as priming your application's data.

The main.js file defines several of durandal's modules to help the application kick start. The define statement helps resolve the modules dependencies so they are available for the function. First the debugging messages are enabled, which send messages about what events the application is performing to the console window. The app.start code tells durandal framework to start the application. The conventions are set so that durandal knows all views and viewmodels are contained in the same named folders, respectively. Finally, the app.setRoot kicks loads the shell using a predefined entrance animation.

define(['durandal/app', 
		'durandal/viewLocator', 
		'durandal/system', 
		'durandal/plugins/router'],
    function (app, viewLocator, system, router) {

    // Enable debug message to show in the console 
    system.debug(true);

    app.start().then(function () {
        router.useConvention();
        viewLocator.useConvention();
        //Show the app by setting the root view model for our application.
        app.setRoot('viewmodels/shell', 'entrance');
    });
});

Views

Views are found in the App/views folder.

shell.html

The shell.html contains the master layout for your HTML. All of your other views will be composed somewhere in side of your shell view. Hot Towel provides a shell with three such regions: a header, a content area, and a footer. Each of these regions is loaded with contents form other views when requested.

The compose bindings for the header and footer are hard coded in Hot Towel to point to the nav and footer views, respectively. The compose binding for the section #content is bound to the router module's active item. In other words, when you click a navigation link its corresponding view is loaded in this area.

<div>
    <header>
        <!--ko compose: {view: 'nav'} --><!--/ko-->
    </header>
     <section id="content" class="main container-fluid">
        <!--ko compose: {model: router.activeItem, 
            afterCompose: router.afterCompose, 
            transition: 'entrance'} -->
        <!--/ko-->
    </section>
    <footer>
        <!--ko compose: {view: 'footer'} --><!--/ko-->
    </footer>
</div>

nav.html

The nav.html contains the navigation links for the SPA. This is where the menu structure can be placed, for example. Often this is data bound (using Knockout) to the router module to display the navigation you defined in the shell.js. Knockout looks for the data-bind attributes and binds those to the shell viewmodel to display the navigation routes and to show a progressbar (using Twitter Bootstrap) if the router module is in the middle of navigating from one view to another (see router.isNavigating).

<nav class="navbar navbar-fixed-top">
    <div class="navbar-inner">
        <a class="brand" href="/">
            <span class="title">Hot Towel SPA</span> 
        </a>
        <div class="btn-group" data-bind="foreach: router.visibleRoutes">
            <a data-bind="css: { active: isActive }, attr: { href: hash }, text: name" 
                class="btn btn-info" href="#"></a>
        </div>
        <div class="loader pull-right" data-bind="css: { active: router.isNavigating }">
            <div class="progress progress-striped active page-progress-bar">
                <div class="bar" style="width: 100px;"></div>
            </div>
        </div>
    </div>
</nav>

home.html and details.html###

These views contain HTML for custom views. When the home link in the nav view's menu is clicked, the home view will be placed in the content area of the shell view. These views can be augmented or replaced with your own custom views.

footer.html

The footer.html contains HTML that appears in the footer, at the bottom of the shell view.

ViewModels

ViewModels are found in the App/viewmodels folder.

shell.js

The shell viewmodel contains properties and functions that are bound to the shell view. Often this is where the menu navigation bindings are found (see the router.mapNav logic).

define(['durandal/system', 'durandal/plugins/router', 'services/logger'],
    function (system, router, logger) {
        var shell = {
            activate: activate,
            router: router
        };
        
        return shell;

        function activate() {
            return boot();
        }

        function boot() {
            router.mapNav('home');
            router.mapNav('details');
            log('Hot Towel SPA Loaded!', null, true);
            return router.activate('home');
        }

        function log(msg, data, showToast) {
            logger.log(msg, data, system.getModuleId(shell), showToast);
        }
    });

home.js and details.js

These viewmodels contain the properties and functions that are bound to the home view. it also contains the presentation logic for the view, and is the glue between the data and the view.

define(['services/logger'], function (logger) {
    var vm = {
        activate: activate,
        title: 'Home View'
    };

    return vm;

    function activate() {
        logger.log('Home View Activated', null, 'home', true);
        return true;
    }
});

Services

Services are found in the App/services folder. Ideally your future services such as a dataservice module, that is responsible for getting and posting remote data, could be placed.

logger.js

Hot Towel provides a logger module in the services folder. The logger module is ideal for logging messages to the console and to the user in pop up toasts.

Resources

Hot Towel SPA on NuGet

Hot Towel also comes as a NuGet package that you can add to an ASP.NET MVC application. If you start from scratch, the template is the way to go. If you have an existing project, you can use the NuGet package (which lacks the start-up hooks that the template has).

Hot Towelette SPA on NuGet

Hot Towel also comes as a NuGet package that you can add to an ASP.NET application (no MVC required). If you start from scratch, the template is the way to go. If you have an existing project, you can use the NuGet package (which lacks the start-up hooks that the template has).

hottowel's People

Contributors

johnpapa avatar nikmd23 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hottowel's Issues

body max-width

Would it be a good idea to use max-width: 1230px instead?
If I use bootstrap row with span* they start collapsing under eachother on wide screens

HotTowelRouteConfig breaks non-breeze webapi controllers

Using the vsix to create a hot towel app, any webapi controllers that are added will not resolve.

This seems to be because a route with hot towel defaults is being slammed to the front of the table so pretty much everything resolves to it. An easy fix is to modify the standard routeconfig default route and remove the hot towel one. Also the BreezeWebApiConfig is a little surprising in its behaviour for anyone who wasn't planning to go solely with breeze.

Was definitely surprised by this behaviour and took quite some time to find the culprit. If it is intended, a comment to explain that standard mvc and webapi conventions have just been nuked would be helpful.

Failed at the [email protected] install script, 'bower install'

Hey John,

I am having an issue installing the npm package of the modular example in your AngularJS Patterns: Clean Code video on pluralsight. I followed the instructions, but when I get to the npm install in the modular folder I am getting the following error (see attached image). Any advice?
npm_error

SignalR

First, Thanks for a nice template.

In SignalR they tell you to put RouteTable.Routes.MapHubs() in Application_Start() before any other routing. With HotTowel I had to move it to here so that I set the MapHubs route before your HotTowel route:

public static void RegisterHotTowelPreStart() {
        RouteTable.Routes.MapHubs();     //  <-- to resolve ~/signalr/hubs

      // Preempt standard default MVC page routing to go to HotTowel Sample
      System.Web.Routing.RouteTable.Routes.MapRoute(
          name: "HotTowelMvc",
          url: "{controller}/{action}/{id}",
          defaults: new
          {
              controller = "HotTowel",
              action = "Index",
              id = UrlParameter.Optional
          }
      );

Pages from sidebar are not loading

Have a little bit of issue where I try to click the view on the side bar menu it loads dashboard (default route). I have updated the config.route , controller and view. Any help would be appreciated. Thanks

Bundles are being registered twice

Both the Global.asax.cs and the HotTowelConfig.cs are registering bundles.

BundleConfig.RegisterBundles(BundleTable.Bundles);

is being called twice

Still no AngularJS-Modular-Demo available on Nuget

Hi John,

I have tried to search for "AngularJS-Modular-Demo" as a package on the VS IDE and on the GitHub and Nuget package site. Nothing could be found.

I did also a filter check in VS 2013 with the following command: Get-Package -Filter AngularJS-Modular -ListAvailable but still nothing.

Could you please either provide a link to where I could find this package or put this on your repository.

Thanks

Xen

Durandal viewmodel routing

Out of the box, the only routes that exist in shell.js are:

router.mapNav('home');
router.mapNav('details');

If you add new views/viemodels, you have to go add them to shell.js.

It would be a lot more useful if you changed it to:

router.mapAuto('viewmodels');
router.mapNav('home');
router.mapNav('details');

So that any new views/viewmodels that are added are picked up automatically.

Even better would be to have an array somewhere of the routes that are visible in the navigation

var navRoutes = ['home','details'];

Then just call mapNav on the routes in that array.

Question more than an Issue

I updated the hottowellete durandal version from 1.1 to 1.2 via nuget and scrolling on IOS seems to have broken - anyone else gotten this problem?

thanks.

-- i resolved this by commenting out--> so this can be closed.

    adaptToDevice: function() {
        //document.ontouchmove = function (event) {
        //    event.preventDefault();
        //};
    }

in durandal/app.js

Add support for ASP.net MVC 5

I'd like to see HotTowel support for the new VS 2013 Web ASP.net MVC 5 project directly.
I tried to use the NuGet package and see if I could get it to work but the references aren't updated to EntityFramework 6 and I got blocked at that stage.

HotTowelConfig method PreStart() should be named PostStart()

Hi John,

Thanks a lot for a wonderful Towel - it really helps in SPA :).

Here is some nitpicking (Minute, trivial, unnecessary, and unjustified criticism or faultfinding - freedictionary.com) issue: The name of the method in HotTowelConfig class is PreStart(), while the method invocation in WebActivator is done at PostApplicationStart.

Thanks again for the useful and time saving template!
/ms440

Routing Issues - API controllers don't work.

From a new project from the HotTowel template vsix, I added new ApiController to it. It doesn't work.

I'm not sure exactly why, but if I remove the HotTowelRouteConfig.cs, then the API controllers work again.

It looks like all that it was trying to do was to change the default controller. In RouteConfig.cs, I just changed "Home" to "HotTowel" instead, and it works just fine.

Am I missing something? Why was a custom route needed?

Also - I added the Microsoft.AspNet.WebApi.HelpPage package. It too failed until I changed the routing as described.

Error: AngularJS-Modular-Demo

npm install error. Please let me know what I can do to resolve this. Thanks, Xen

173007 verbose unsafe-perm in lifecycle true
173008 info [email protected] Failed to exec install script
173009 error [email protected] install: bower install
173009 error Exit status 1
173010 error Failed at the [email protected] install script.
173010 error This is most likely a problem with the AngularJS-Modular-Demo package,
173010 error not with npm itself.
173010 error Tell the author that this fails on your system:
173010 error bower install
173010 error You can get their info via:
173010 error npm owner ls AngularJS-Modular-Demo
173010 error There is likely additional logging output above.
173011 error System Windows_NT 6.2.9200
173012 error command "C:\Program Files\nodejs\node.exe" "C:\Program Files\nodejs\node_modules\npm\bin\npm-cli.js" "install"
173013 error cwd C:\play
173014 error node -v v0.10.33
173015 error npm -v 1.4.28
173016 error code ELIFECYCLE

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.