A lot of talk has been happening over the new MVC 4 display modes feature. If you don’t know what it is, the display modes feature controls the display to the current user, switching which view is being displayed by the user by running a specific condition. What this means is I can setup a condition to target the iPad, and then display an iPad-specific view to the user, instead of the standard view. The convention for a display mode is: viewname.<placeholder>.cshtml (assuming we’re using Razor), where placeholder is an alias passed to the constructor of the display mode. Below is a sample display mode class that I adapted and modified from a sample on the web and is available here:
Every time a request is made to the server, the display mode condition is checked to determine if the scenario is appropriate for an alternative display. If the user agent matches a mobile device, MVC serves up the view with .Mobile.cshtml or .Mobile.aspx in it’s name, if one can be found. If no view exists with that name, then the default is returned.
I did run into one problem; MVC was ignoring my requests. In inspection of the display modes collection, I noticed the ASP.NET MVC framework already had a mobile display mode implementation present. I had to remove that one and add a new one, as I did below in the Global.asax page. Interestingly enough, by researching this I did find that it uses the DefaultDisplayMode class to provide the mobile view, meaning the same class is used by ASP.NET MVC to detect standard and mobile requests.
Note that display modes can be for anything; we could have a display mode that matches the iPhone user agent, and displays an iPhone-specific view. Or a display mode could be not device-specific, but based on other information about the current request. The possibilities are limitless.
One might ask why customize the display mode at all? I personally ran into an issue using the opera mobile emulator; the emulator was not supported in the default implementation. Adding a condition to check for the “Opera Mobi” user agent resolved that problem.