In a recent project I had to come up with a clever way to sniff the browser type out and then properly display either a mobile or native web site. I researched a few different solutions, but after conversing with my boss, @jimzim, he had a prototype of 51 Degrees Foundation in MVC3 whipped up in no time.
The Quick & Dirty
Basically the nuts and bolts of it is that the FiftyOne.Foundation intercepts your request object and adds several properties for you to use to determine the device type. Most notably the bool:
In MVC3 we created two different layout pages, _Layout.cshtml ( the MVC3 default) and _LayoutMobile.cshtml. This allowed us to modify the _ViewStart.cshtml file like so:
The only difference between the layouts was the stylesheet references, one for mobile and one for native and then the viewport modifications I made to lay it out properly for the mobile device:<meta name=”viewport” content=”width=device-width,height=640, initial-scale=1, maximum-scale=1″ /> Clearly you can see where this is going. If you can’t. Quit now. :-)
For the configuration, use NuGet to add the Library package reference (Just search 51):
If you are the command-line guy (kind of like “Blackberry guy” but more militant) use:
PM> install-package 51Degrees.mobi
- add the FiftyOne.Foundation reference for you
- add an App_Data directory (unless you have one already)
- add 3 files in the App_Data directory: Log.txt, web_browsers.patch.txt and wurfl.xml.gz
- add a configSection group in your web.config with two sections, one for the log and one for the wurfl reference. More on the wurfl reference here
Inside the config you will now see a myriad of options. I kept it simple and just included the log file path, wurfl file path and browser patch.
The Lone Gotcha
So, you think you are all setup. Locally it will run fine. But if you try to deploy this somewhere, like say Azure, it will fail because you didn’t do one thing:
Rookie mistake. Just set the properties of the wurfl.xml.gz file for Build Action to “Content” and Copy always for the Copy to Output Directory if it’s not already set.
This couldn’t have been simpler. We created one layout with two different styles based on mobile or native browsers and we pulled it off successfully. The power of MVC3 and NuGet saved the day, along with a little help from 51Degrees.