Pages

martedì 7 maggio 2013

MVC 4 and different views for mobile devices

I've just discovered a really interesting feature of ASP.NET MVC 4 that will help web developers to create websites that displays in a good way on all devices.

The main idea is to create different version of the same view: the standard one for desktop and another one optimized for smartphones and tablets. It's even possible to create additional versions of the same view for a specific User-Agent.

Doing this is very easy. Let's start with the most basic example: creating two different layouts for desktop and mobile version.

All we need to do is to create a copy of the layout (in a standard project you can find it in the path "Views\Shared\_Layout.cshtml"), rename it "_Layout.Mobile.cshtml" and apply the changes on that particular file.

with this naming convention MVC will AUTOMATICALLY choose the file"_Layout.Mobile.cshtml" to render the page only in case of mobile device,otherwise it will choose the classic "_Layout.cshtml"

you can use this naming convention not only for Layouts but for ALL the Views, including Partials.

".Mobile" is the suffix provided by default but we can create additional ones to render the same view in a different way for a specific browser or device.

To add a suffix we need to change the "Global.asax" file adding this instruction to the method "Application_Start":


DisplayModeProvider.Instance.Modes.Insert(0, 
//indicate here the new suffix
new DefaultDisplayMode("iPhone")
{
 //indicate here the condition that need to be true
 //to pick up the views with the suffix
    ContextCondition = (context => context.GetOverriddenUserAgent().Contains("iPhone"))
});

Using this instruction we will be able to create an additional copy of the layout named "_Layout.iPhone.cshtml" that will work ONLY on iPhones.

Nessun commento:

Posta un commento