In a recent post I talked about the NuGet that allows you to do MVC4-style mobile views in MVC3. My cocktailsrus.com beta site is now live and in the process of testing, and I’ve found an issue with the NuGet (or, more accurately, with the underlying ASP.NET property it relies on). I thought it would be a good idea to share the problem – and my solution – with you.
The problem is that the ASP.NET isMobileDevice property is detects some mobile devices, but by no means all. So when I checked my site in an iPhone, I got the mobile version. When I checked it using Android, I got the full version – not what I wanted at all. I came across this problem in MVC, but because it’s an underlying ASP.NET problem, it would apply to Web Forms in exactly the same way.
Here is how the NuGet determines which view to return:
As you can see, the constructor passes through a predicate which uses the isMobileDevice property. The methods that do the work of returning the appropriate view to the appropriate device use this predicate. Which is great…. Unless the property is not being set correctly. Unfortunately, that’s exactly what happens with Android (and other) mobile devices. ASP.NET doesn’t recognize them, so neither does the NuGet.
My solution is definitely on the quick and dirty side. I only really care about supporting iPhones and Androids. With other mobile devices, I’m willing to take pot luck on isMobileDevice detecting them correctly. So all I needed to do was find out if the device was either recognized as a mobile device, or was an Android device.
Here is my amended version of the NuGet, which adds a second test to the predicate, checking whether the the UserAgent contains the word “Android”:
I tested it, and received the correct version on both iPhone and Android devices – so it’s solved my problem. The next step is to tidy it up and use a constant instead of a string literal. And, of course, to wait and see if the next version of ASP.NET does a better job of detecting mobile devices. If not, then I’ll have to work up a more fully featured fix (like looking into updating the underlying definition files ASP.NET is using to determine what is a mobile device, or at least checking the UserAgent contains “palm”, “blackberry” etc.).
For other related information, check out these courses from Learning Tree: