Archive for April, 2011
Using pjax with ASP.Net MVC3
by Jim Geurts on Apr.11, 2011, under Web Development
I was recently introduced to the pjax project and wondered how hard it would be to use it with asp.net. It turns out that it takes next to no effort to have a basic asp.net mvc3 razor application support pjax.
Overview
pjax uses ajax to reload a portion of your page. This is nothing new, but the “p” part of pjax stands for pushState. PushState is a new feature of Html5 that allows you to modify browser history, without messing around with hash values. So pushState gives you the speed boost of using ajax to update just part of your page, while offering a traditional experience for browsers like IE. According to caniuse.com, Firefox 4+, Safari 5+, Chrome 8+, iOS 4+, and Android 2.2+ all support pushState.
Demo
The github home for the jQuery plugin for pjax has an overview of available options and usage. The project also has a demo hosted on heroku that will give you an idea of how pjax works and some ideas for how you can use it in your application(s).
My version using Asp.Net MVC3
While my version may not be as sexy as the Ruby example, it’s simple and allows you to still use content sections for things like javascript. I just check for the X-PJAX header in the _ViewStart.cshtml, where my layout is specified for the views. If the X-PJAX header is specified, then the views should use a “chrome-less” layout. Otherwise, they should use the normal layout.
The _ViewStart.cshtml file looks like:
@{
if (Request.Headers["X-PJAX"] != null) {
Layout = "~/Views/Shared/_PjaxLayout.cshtml";
} else {
Layout = "~/Views/Shared/_Layout.cshtml";
}
}
My _PjaxLayout.cshtml layout file is very basic and just contains a tag for the page title and the content body section:
<title>@ViewBag.Title</title> @RenderBody()
Additional thoughts
If you have javascript that needs to run on the page, you could easily add @RenderSection(“Script”, false) after @RenderBody(). Just keep in mind that the pjax plugin only updates one container on the page. So if you have multiple html content sections that need updating, you would need to wrap them in a container that could be updated in one call.
Download
If you’re interested, feel free to take a look at the asp.net mvc3 pjax demo project I created.