Jan 18, 2012

Mobile Capable View Engine- Custome View Engine

One of the nice feature of ASP .NET MVC framework is its Extensibility. I created a custom view engine which changes view location based on the device from where its being accessed.

In the following code I update view name with mobile specif view, if the request is being originating from mobile devise

 public class MobileCapableRazorViewEngine : RazorViewEngine
    {
        public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)
        {
            if(IsMobileDevice(controllerContext))
   {
    viewName = viewName + ".mobile";
    masterName = masterName + ".mobile"
   }
        }
 }
 
 private static bool IsMobileDevice(ControllerContext controllerContext)
 {
  //ASP.NET’s built-in browser detection support may not be sufficient for all applications specifically in case of latest devices
  //add the open source 51Degrees.mobi Foundation library to your project
  //you can also use UserAgent controllerContext.HttpContext.Request.UserAgent
  return controllerContext.HttpContext.Request.Browser.IsMobileDevice;
 }


And in the global.asax remove the default view engine and add our custome view engine.

 //Remove default RazorViewEngine and add MobileCapableRazorViewEngine
 ViewEngines.Engines.Remove(ViewEngines.Engines.OfType().First());
 ViewEngines.Engines.Add(new MobileCapableRazorViewEngine());

 

Similar approach can be taken for FindPartialView.

No comments:

Post a Comment