Click here to Skip to main content
15,867,568 members
Articles / Web Development / HTML
Tip/Trick

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

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
13 Apr 2014CPOL2 min read 19.2K   10   1
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:

    C#
    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:

    JavaScript
    @{
        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:

    HTML
    <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:

    HTML
    <div id="bodyContent">
         @RenderBody()
    </div>
  5. Create the JavaScript responsible for the AJAX based navigation and history state management:
    JavaScript
    $(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:

Image 1

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.

Image 2

License

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


Written By
Software Developer (Senior) Reckitt Benckiser
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionHow about VS2013, VS2015 version? Pin
tatran.eu@gmail.com28-Jan-16 1:18
tatran.eu@gmail.com28-Jan-16 1: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.