In an earlier post, I blogged about the NuGet that allows ASP.NET MVC3 to take the same approach as MVC4 to delivering different views for mobiles and standard browsers. I’ve now fully implemented this on my cocktails site, and come across some interesting complications when combining it with Ajax and progressive enhancement.
This is the mobile site:
This is the standard version:
The site uses Ajax in a number of ways – some present no problem, but others are more challenging. Autocomplete functionality was easy to implement – I just used jQuery UI on on both the mobile and the standard site and returned the appropriate JSON data from an ActionResult.
The bigger challenge arose when I wanted to use Ajax more extensively in page navigation – and I ended up having to adopt two different solutions.
Normally, I would detect that a request is using Ajax, and if so return the partial view, otherwise return the full version. The trouble is, jQuery mobile uses Ajax extensively for page navigation – so the Ajax version intended for use with non-Mobile devices could end up being sent to the mobile site, where it would not work correctly.
The first solution I adopted was to return the partial view only if it was both using Ajax and a standard browser, like so….
This works pretty well – unless the request comes from a form and uses multipart data (e.g. uploading an image). I use the forms plugin to ‘ajaxify’ forms, and for some reason ASP.NET MVC does not pick up that the request is Ajax when it’s encoded for multipart data. I found various suggestions to deal with this online (e.g. passing in the iframe parameter), but none of them worked for me. So I switched to plan B – providing an alternative version of the method.
The end result is online now as the beta version of the site. The standard version uses HTML5, jQuery 1.7 and Ajax navigation through progressive enhancement. The mobile version uses jQuery Mobile 1.0 and has a completely different UI, but the same underlying functionality. I’m really enjoying developing with jQuery Mobile – it really is an excellent new tool in the Web developer armory.
For other related information, check out these courses from Learning Tree: