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:
- 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>
- 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. - 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>
- 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>
- 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.");
}
});
}
}
- 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.