Low impact Ajax with jQuery and ASP.NET MVC

Here's a simple way to avoid postbacks in your site, still be SEO friendly and degrade gracefully to JavaScript free browsers (and handle middle clicks and copy&paste) in ASP.NET MVC using jQuery.

First, we'll create an alternate MasterPage called No.master with no content, only one ContentPlaceHolder:

<asp:ContentPlaceHolder ID="MainContent" runat="server" />

Now, we're able to tell via HTTP Headers if a Request is an Ajax Request, so we'll write a new method in our Controller Base class to toggle the master page:

protected string GetMasterPageName() { if (this.IsAjaxRequest()) return "No"; return "Site"; }

And now, whenever we return a View in our Controllers, we'll use the overload that takes in the name of a View

return View("Edit", GetMasterPageName(), postServices.GetByID(id))

So when a request comes in normally, we are returned full mark-up.  If the request is AJAX, we only return HTML for that view.

We won't modify the url of our links, however we'll give them all a class so we can grab then in jQuery.

<a href="/Post/Show/<%=post.ID %>" class="ajaxLink"><%= post.Subject %></a>

Then we'll wire a method called displayLink to all our ajaxLinks' click event handlers:

$('.ajaxLink').click(displayLink);

And in that function we'll make an AJAX call to the link's target (its href attribute value) using the jQuery $.get method, update our main content area and return false in order to cancel the click event of the link:

displayLink = function() { $.get($(this).attr('href'), function(response) { $('#mainContent').html(response); }); return false; };

And that's it.  I would (and did) refactor the JavaScript and add a loading graphic, but I'm just awestruck at how you can Ajaxify an application in ~12 lines of code.

Comments

# re: Low impact Ajax with jQuery and ASP.NET MVC
Gravatar It's a good trick, I bookmarked up front.
Thanks for sharing !
Left by cypher on 11/12/2008 11:32 AM
# re: Low impact Ajax with jQuery and ASP.NET MVC
Gravatar On second thoughts, I have trouble implementing this.

Could you please provide a code download ?

Cheers.
Left by cypher on 11/13/2008 3:55 AM
# re: Low impact Ajax with jQuery and ASP.NET MVC
Gravatar sure, i'm doing this in this blog engine:

http://code.google.com/p/tribality/

relevant code:

http://code.google.com/p/tribality/source/browse/trunk/Tribality/Controllers/PostController.cs

http://code.google.com/p/tribality/source/browse/trunk/Tribality/Content/jquery.plugins.js?r=2
Left by len smith on 11/14/2008 6:02 AM

Leave Your Comment

Title*
Name*
Email (never displayed)
 (will show your gravatar)
Url
Comment*

Please add 3 and 8 and type the answer here:

Preview Your Comment.