Ajax your ASP.NET MVC Application with Pathbinder

Gracefully Degrading AJAX Page Loading

The goal of this article is to demonstrate a technique for enabling AJAX loading of content for ASP.NET MVC web applications. The technique uses Pathbinder. It gradefully degrades so that in browsers without JavaScript, the users will navigate pages as normal. The method of making this happen involves translating internal site links to have a ‘#’ in front of the href path on pageload and then using AJAX to load these pages into the content area of the page without reloading the entire page. For users who do not have JavaScript enabled, the links will work like normal links. On the server-side, we must respond to AJAX requests by rendering the page without its master page. For normal requests, we will render the page with its master page.

Pathbinder

Pathbinder is a jQuery framework packaged with couchapp.  It was inspired by sammy.js.  Pathbinder makes it easy to respond to changes in URL paths with JavaScript event handlers.  Why is this relevant as changes to URLs usually reload the page? URL Paths refer to ‘#’ portions of the URL. The part of the URL following the ‘#’ is used to store the state of a page and changes without reloading the page. When a user clicks on a link to ‘#/foo’, the path in the URL will change but the page will not reload.  Pathbinder will trigger events registered for this URL path to allow the application to modify the page.

The HTML

Say Hello

The JavaScript

// Register event 'hello-world' to be triggered on '#main' when URL path changes to #/hello-world
// note that the '#' should not be included in the URL path when registering the event
$(“#main”).pathbinder(“hello-world”, “/hello-world”);

// Bind an event handler to the event 'hello-world'
$(“#main”).bind(“hello-world”, function() {
	$("#main").html(“<p>Hello World</p>”);
});

Altering Standard Link to Load Pages with AJAX

Now that we have a basic understanding of pathbinder, it is time to write the JavaScript that will change the regular links on
a page into AJAX links. We will write a function called handleAnchor that will perform three tasks: bind an event-handler named
after the anchor’s href to the ‘#main’ content area that AJAX loads the page into the content area, register the event in pathbinder
on the ‘#main’ content area, and alter the anchor’s href to have a ‘#’ infront of the url in the href attribute.

   var handleAnchor = function(indx, anchor) {
      var href = $(anchor).attr('href');

      if (!href) { return; }

      $("#main").bind(href, function() {
        $.ajax({
          url: href,
          success: function(data, textStatus) {
            $("#main").html(data);
          }
        });
      });

      $("#main").pathbinder(href, href);

      $(anchor).attr('href', '#'+href);
  };

  $('a').each(handleAnchor);

Talk about us!