Joseph Michael Pesch
VP Programming

Convert Standard MVC Website to SPA (Single Page Application) Using Sammy.js

by 19. February 2015 07:17

Step One: The Layout Page

For MVC the layout page is a template that ASP.NET uses to render a single HTML document by merging it with the markup in a view page.  In a SPA, the Layout becomes a shell page into which the view's markup is loaded via AJAX calls. The Layout page's lifespan is now the user's session, rather than just the lifespan of the page, so be careful what you scope at this level; the safety net of a page refresh that cleans up after us is gone, and browser memory leaks are distinctly counter-excellent in nature.

To convert a standard MVC website to SPA we'll use NuGet to add Sammy.js to our project. Sammy (among other things) is a jQuery-dependent JavaScript framework which lets us add URL routing to the client side of our app.

Once we've brought in Sammy, we'll add it to a bundle (along with jQuery) in BundleConfig.RegisterBundles:

bundles.Add(new ScriptBundle("~/js/mvc-spa").Include(

Then we'll render the bundle at the bottom of our Layout page:


We'll also need to designate the area of the Layout where the view content will be loaded by finding the element we are currently calling RenderBody and giving it a unique id. For this example, let's go with "page".

<!-- ... -->
<section id="page">
<!-- ... -->    

Step Two: Go Partial

Next, we need to go through our views, and, with the exception of the Home/Index view, convert each to a Partial View.

Unlike vanilla MVC Views, Partial Views are not merged with the Layout page to render as complete HTML documents. When you make a controller request that returns a Partial View, the response is merely an HTML fragment–precisely what we're looking for in a SPA page.

To convert a View to a Partial, simply change the View call to a call to PartialView in its corresponding Controller Action:

public class SpaFtwController : Controller {
    public ActionResult Index() {
        return PartialView();

As I may have mentioned above, do not convert your default view to a partial. This view is the "single page" in "single-page application", and it still needs to render as a complete HTML document, just the once. However, we should move this Index view's content into a separate Partial View, and replace it with some sort of splash content that will only display while our app is still loading. More on that in the next step.

Step Three: One Route to rule them all

The typical usage of Sammy is to describe multiple hash-based routes, along with the js to be executed when the user navigates to them. What we're going to do in this case, though, is create a solitary Sammy route that acts as a pass-through to the existing MVC routing already in place on the server-side.

For example, a request to /#/spaftw would load the content from /SpaFTW into our app. Using fragment identifiers for routing is a classic SPA technique; it changes the browser's URL without causing a whole page request, while also allowing the back button to still work as expected, and enables deep-linking into the app.

Here is a module that contains the code to do just this. We'll add it to our project in a file named Routing.js.

var Routing = function (appRoot, contentSelector, defaultRoute) {
function getUrlFromHash(hash) { var url = hash.replace('#/', ''); if (url === appRoot) url = defaultRoute; return url; }
return { init: function () { Sammy(contentSelector, function () { this.get(/\#\/(.*)/, function (context) { var url = getUrlFromHash(context.path); context.load(url).swap(); }); }).run('#/'); } }; }

Let's unpack that. See the this.get call about two-thirds of the way down? That's Sammy's bread and butter. We're using a regular expression to describe a route URL that captures any href beginning with '/#'. When a request is made for a URL matching this expression, Sammy intercepts it and runs the function that we've passed as get's second parameter. This function grabs this path, strips out the hash, makes an AJAX request for the Partial View for that URL, and swaps it into the element designated by contentSelector. Which, of course, will be our content area in the Layout page.

Finally, we need to wire this into our Layout page. Add Routing.js to our bundle, after Sammy.js:

bundles.Add(new ScriptBundle("~/js/mvc-spa").Include(

Then, add the following script block to the Layout page, after rendering the bundle:

$(function () {
    var routing = new Routing('@Url.Content("~/")', '#page', 'welcome');

This instantiates a Routing instance with the root URL for the application (this becomes important if our app is deployed anywhere other than '/'), the selector of our content area ('#page'), and the route to default to when the user navigates to the root of the app. This should be the Partial View that inherited the original content from our Home/Index view, in step two.

Original version of this modified post published here:



C# | MVC

Comments are closed