Improved Device Detection with ASP.NET

This is a follow up to my last post where I did a quick-and-dirty hack to get around the limitations of ASP.NET’s built-in isMobileDevice property.

At the end of that post, I said I was going to wait and see if Microsoft did a better job next time around before I went to the trouble of improving my solution. Well, it didn’t work out that way. You see, even if I hadn’t disliked leaving a quick-and-dirty fix in place, it turned out that there was another complication that meant I really needed to provide a proper solution.

The app uses Ajax extensively (and explicitly) in the non-mobile version in order to give a better user experience. It also uses Ajax implicitly in the mobile solution, as jQuery mobile automatically converts links and forms into Ajax calls unless you tell it not to do so. What I hadn’t taken into account in my quick-and-dirty approach was that I wasn’t just detecting mobile devices inside the view engine – I also needed to detect them in order to provide partial pages to Ajax calls in the non-mobile Web version.

The app delivers three kinds of content:

  • Full Web Pages
  • Full Mobile Pages
  • Partial pages for non-mobile Ajax calls

Unfortunately, as jQuery mobile also makes Ajax calls, when mobiles were not detected by the built-in isMobileDevice property, I was returning the partial page when I should have been returning the full mobile page.

So back to the drawing board.

And since I was now going to have to do things properly, I decided to support all the major mobile platforms, not just Android.

I created a new static method isMobileDevice() which accepts an argument of type HttpContextBase and checks both the built-in isMobileDevice property and series of string constants. I then call this method from inside the ViewEngine Nuget and also from my controllers when detecting if the call is an Ajax call.

Here is the key method:

Sample code from method detecting mobile devices

And here is one of the calls to the method:

Sample code calling the new method

If you want the full code, I’ve placed it online as devicedetector.txt. I hope you find it useful.

Kevin Rattan

For other related information, check out these courses from Learning Tree:

Building Web Applications with ASP.NET MVC

Building Web Applications with ASP.NET and Ajax

Type to search

Do you mean "" ?

Sorry, no results were found for your query.

Please check your spelling and try your search again.