LenPopLilly
LenPopLilly

Reputation: 1227

How to implement history.js with ASP.NET MVC

Can anyone point me in the right direction with implementing the History.js gist with MVC project over at https://github.com/browserstate/history.js

Im just getting to grips with MVC and im considering full Ajax app with Ajax nav or standard nav (urls) with content loaded via Ajax, not sure which way to go but help appreciated.

Im MVC newbie so please forgive me if this is a basic or obvious question

Upvotes: 4

Views: 2866

Answers (2)

Omid.Hanjani
Omid.Hanjani

Reputation: 1522

copy from this link: Make an MVC Application into a SPA with AJAX and History.js (from Edson_Ferreira)

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!

Upvotes: 1

ggozad
ggozad

Reputation: 13105

If you are an MVC newbie, you might as well use a library to help you do it. Backbone does that for you in a very clean way and also supports history through its router.

Upvotes: 1

Related Questions