Click here to Skip to main content
12,749,754 members (34,316 online)
Click here to Skip to main content
Add your own
alternative version


9 bookmarked
Posted 12 Apr 2014

Make an MVC Application into a SPA with AJAX and History.js

, 13 Apr 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This tip will demonstrate how to create a SPA using an MVC Application, AJAX and History.js


This tip aims to demonstrate how to create a Single Page Application (aka SPA) using MVC, AJAX and History.js.

To get the full source code of a working example, download and install the Visual Studio extension I've put together for MetroUI 2.0.

It's available to download from Visual Studio Gallery and the URL is the following:

How Do You Do It?

Let's describe how this can be achieved using the technologies mentioned above:

  1. Let's start with the Layout file. We need to add the following references to our Layout page (_Layout.cshtml):
    • <script src="~/Scripts/jquery-2.1.0.js "></script>
    • <script src="~/Scripts/jquery.history.js"></script>
    • <script src="~/Scripts/jquery.showLoading.js"></script>
  2. Create the Controller(s) and associated Views that we are going to navigate to:

    This is how an MVC Controller method that returns a View will look like:

    public ActionResult Rating()
        ViewBag.IsAjaxRequest = Request.IsAjaxRequest();
        return View();

    The reason why we need to specify the dynamic property "ViewBag.IsAjaxRequest = Request.IsAjaxRequest();" is because this information will be used to disable or enable the associated layout with the view being returned.

    The '_ViewStart.cshtml' will be responsible for managing this. The file should look like this:

        if (ViewContext.ViewBag.IsAjaxRequest == true)
            Layout = null;
            Layout = "~/Views/Shared/_Layout.cshtml";    
    This is required to enable the user to type the URL on the address bar and not get a PartialView, but instead, get the expected full page with the layout applied on top of it.
  3. Prepare your links to be managed via AJAX:

    On the Anchor Element, we need to add a class that will be used later to bind the 'Click' event using jQuery. Also, we need to add a 'data-ref' attribute so we can store the URL associated with this link.

    Because this is an MVC application, we can use the '@Url.Action' helper to assist us in creating the URL; the 1st parameter is the 'View' and the 2nd parameter the 'Controller'.

    This is how it should look:

    <a href="#" class="ajaxLink" data-href="@Url.Action("Rating", "Visualisation")" data-title="Rating">Rating</a> 
  4. Prepare a container on which the views will be inserted.

    The _Layout.cshtml file should have the following lines of code in it:

    <div id="bodyContent">
  5. Create the JavaScript responsible for the AJAX based navigation and history state management:
    $(function () {
        var contentShell = $('#bodyContent');
        var History = window.History, State = History.getState();       
        $(".ajaxLink").on('click', function (e) {        
            var url = $(this).data('href');
            var title = $(this).data('title');
            History.pushState(null, title, url);
        History.Adapter.bind(window, 'statechange', function () {
            State = History.getState();
            if (State.url === '') {
        function navigateToURL(url) {        
                type: "GET",
                url: url,
                dataType: "html",
                success: function (data, status, xhr) {
                error: function (xhr, status, error) {
                    alert("Error loading Page.");
  6. Add the reference to this JavaScript file in the _Layout.cshtml file after the views container:
    <div id="bodyContent">
    @RenderSection("scripts", required: false)
    <script src="~/Scripts/App_Scripts/Layout.js"></script>

That's it!

For a full working example, download the Visual Studio extension I've put together for the Metro UI 2.0 CSS framework.

Once you've installed the Project Template, create a new Project and choose the MetroUI.MVC project template:

After you've created a new project using this template, right-click on the Solution node and select the option 'Enable Nuget Packadge Restore'.

After doing this, all associated Nuget packadges will automatically be downloaded and applied when you build the solution.


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


About the Author

Software Developer (Senior) Reckitt Benckiser
United Kingdom United Kingdom
No Biography provided

You may also be interested in...


Comments and Discussions

QuestionHow about VS2013, VS2015 version? Pin 2:18 2:18 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170215.1 | Last Updated 13 Apr 2014
Article Copyright 2014 by Edson_Ferreira
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid