One of the new features of the Microsoft ASP.NET MVC 4 framework is the concept of display modes. By default the framework uses the display mode functionality to “dynamically” select the mobile version of a view ( when present ), when you’re site is viewed on a mobile device.
In short this means it will use the
<viewname>.mobile.cshtml/.vbhtml file as the view when available, and if it’s not available it will fall back to the normal
<viewname>.cshtml/.vbhtml file. (I’m assuming you are using Razor syntax for your views.).
There are tutorials (like in this video on channel 9) that show how to extend this functionality to create a view for a specific device, like an iPhone or iPad. But this is just one of the possibilities.
Just the other day at the office, I’ve had to rewrite a website to support mobile devices. It’s been written on top of ASP.NET MVC 2, so I thought it was only logical to rewrite it with ASP.NET MVC 4. Seems to me like the obvious path to choose, until I took a good look at the way the current site worked.
The site was written in a way that it could be loaded from multiple domains, and used a different set of views and resources based on the host header. To get that done in MVC2 I’ve created my own ViewEngine derivative at the time. As I didn’t want to do that again ( and potentionally lose Razor syntax goodness etc.. ) in this version, it was a challenge to get my head around it, but I’ve got it working like a charm. The key player in the solution is the MVC 4 DisplayModes functionality.
In short: If you can use the display modes to select a different view based on the user agent, you can do more-or-less the same based on the host header. Now I know there are multiple ways to get this done, but as I had to support an arbitrary configurable amount of “themes”, I chose to do it on a more-or-less centralised approach. Summarized I’ve created 2
DefaultDisplayMode derivative classes and overrode the
GetDisplayInfo method to incorporate the ‘load the theme based file’ logic. I’ve created 2 classes, because I wanted to separate the mobile and the non-mobile logic, but you could do it in one if you’d like. All I’ve had to do after this is to insert them in the DisplayModes collection so they will be used by the MVC framework.
I’ll be posting a more elaborate version (including some source code) of the solution shortly. But for now, I hope you’ve got the idea how I’ve tackled it.