ASP.NET MVC – Adding RequireJS/Backbone/Marionette to your solution

Recently, while build a website on Azure, I needed a quick, simple login mechanism. There is an ASP.NET forms based authentication template, so this was pretty straightforward. All you have to do is to create a website based on the template and viola!, you have a login. However, if only life is so simple. The issues arose when I wanted to integrate a single page application architecture with RequireJS and Backbone.js/Marionette.js. A single page application architecture is a Web Page the likes of Gmail or Facebook where a single page opens up and then all the functionality that you require is available from that page without you needing to navigate out of that page. There are a few templates that already have backbone included but they don’t have all the pieces that I required i.e. requirejs, backbone and marionette. I already had all my single page architecture code in a folder called “public”, so I wanted the least amount of hassle to integrate this.

After some mucking around, this is what I figured out:

Simply go and delete most of the content from the folder Home/index.cshtml. This page is shown only after the user has logged in, so you can host the entire single page HTML app in there. After you have cleaned this page out, simply copy paste the require.js main function call in here. In my case, this looked somewhat like:

    Note that all the code below resides in a completely separate directory called public.
    This way, all my JavaScript and HTML code resides in a folder that has got nothing to do with ASP.NET MVC
    and hence has clean separation. I could easily take this code and port it over to node.js or other webservers.
<link href="@Url.Content("~/public/scripts/vendor/bootstrap/css/bootstrap.min.css")" rel="stylesheet" type="text/css"/>
<link href="@Url.Content("~/public/scripts/vendor/bootstrap/css/bootstrap-theme.min.css")" rel="stylesheet" type="text/css" />

<!-- Note that the following call loads up the requirejs and loads up main.js which contains the app router -->
<script data-main="public/scripts/main" src="public/scripts/vendor/requirejs/require.js"></script>

<!-- This div is used by main.js to load up the application in the div with id=dashboard-->
<div id="dashboard"></div>

The cool thing about keeping all the HTML templates and JavaScript in a separate directory such as public is that this method works for any JavaScript libraries – and you don’t need to depend on any ASP.NET templates that ONLY integrate a specific set of libraries.

Leave a comment

Your email address will not be published. Required fields are marked *