Friday, April 20, 2012

Instant MVC 3 Mobile App

Have you been pondering getting into mobile development, but have been procrastinating, and making excuses to yourself about how little time you'll have to devote to it, the steep learning curve, etc?  Yeah, me too.  That is, until I found the simple but awesome "Mobile Ready HTML5" template using Visual Studio Extension manager.  Its a fully functioning MVC 3 application template that is "mobile ready" out of the box, and allows you to easily create your own mobile views for a new or existing MVC 3 app.

The elegant key to its functionality is the subclassing of the System.Web.Mvc.RazorViewEngine, overriding the "FindView" method (Figure 1), and deciding on which View to serve up based on the browser type.  This prevents having to change any code in your controllers, keeping things clean.

Figure 1
using System.Web.Mvc;

namespace Web
{
    class MobileViewEngine : RazorViewEngine
    {
        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            ViewEngineResult result = null;
            var request = controllerContext.HttpContext.Request;

            //Determine if this is a mobile browser
            //IsSupportedMobileDevice is an extension method which queries the UserAgent
            if (request.IsSupportedMobileDevice() && ApplicationHelper.HasMobileSpecificViews)
            {
                //Get mobile view
                string viewPathAndName = ApplicationHelper.MobileViewsDirectoryName + viewName;
                result = base.FindView(controllerContext, viewPathAndName, masterName, true);
                if (result == null || result.View == null)
                {
                    result = base.FindView(controllerContext, viewPathAndName, masterName, false);
                }
            }
            else
            {
                result = base.FindView(controllerContext, viewName, masterName, useCache);
            }
            return result;
        }
    }
}
To create your mobile views, you'll simply need to create a folder called "Mobile" (or anything else, as it's configurable) under the existing Views folder, like so:


It's all downhill from there. I made a couple changes and additions to the UserAgent check, but aside from that, this template will have you up and running with an MVC 3 mobile app in no time.

To get it from Visual Studio:
1. Open extension manager from Tools/Extension Manager
2. Goto Online Gallery, and search for "Mobile Ready HTML5"
3. Click Download.

To get it from a browser:
Go here: http://visualstudiogallery.msdn.microsoft.com/9df9c61c-4d90-43e5-9aa1-a58786b7a1e4.

Thanks to Sammy Ageil for putting this together.  He's got some more details and instructions on his site: http://www.sammyageil.com.

No comments:

Post a Comment