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

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

, 13 Apr 2014
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

Introduction

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;
        }
        else
        {
            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">
         @RenderBody()
    </div>
  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) {        
            e.preventDefault();        
            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 === '') {
                return;
            }
            navigateToURL(State.url);
        });
    
        function navigateToURL(url) {        
            $('#bodyContent').showLoading();
            $.ajax({
                type: "GET",
                url: url,
                dataType: "html",
                success: function (data, status, xhr) {
                    contentShell.hideLoading();
                    $('#bodyContent').hide();
                    contentShell.html(data);                
                    $('#bodyContent').fadeIn(1000);                
                },
                error: function (xhr, status, error) {
                    contentShell.hideLoading();
                    alert("Error loading Page.");
                }
            });
        }
    } 
  6. Add the reference to this JavaScript file in the _Layout.cshtml file after the views container:
    <div id="bodyContent">
        @RenderBody()
    </div>
    @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.

License

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

Share

About the Author

Edson_Ferreira
Software Developer (Senior) Amtech Group
United Kingdom United Kingdom
No Biography provided
Follow on   Google+   LinkedIn

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 13 Apr 2014
Article Copyright 2014 by Edson_Ferreira
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid