Tuesday, July 9, 2013

Using ASP.NET MVC 4 to render customized mobile views

In ASP.NET MVC 4, Microsoft introduced a new feature that allows easily customizing the rendering of Views based on the User Agent string.  This is especially important when working with Mobile devices. 

In ASP.NET Web Forms, we typically had to write some special browser detection code to determine the browser platform and then specially render the screen in order to support the Mobile device.

However, in ASP.NET MVC 4, Microsoft has made this whole process significantly easier!  In ASP.NET MVC 4, through the MVC Design Pattern, we simply have to create a new view to support the Mobile device while our Controller and Model information can remain the same. 

This can be easily done by simply creating a new view with an extension of .Mobile.cshtml (in the case of Razor views).  Therefore, for example, if you wanted to customize the layout for desktop vs. mobile devices, beneath the Views/Shared folder, you could simply create a new View named _Layout.Mobile.cshtml.  ASP.NET MVC 4 will then automatically detect the browser’s User Agent String and render the appropriate view accordingly. 

Just to clarify further, your Views structure should look something like the following screenshot:

MVCMobileViews 

Hopefully migrating to ASP.NET MVC 4 from ASP.NET Web Forms should make it significantly easier to now support mobile devices for your Web Applications.

No comments:

Post a Comment