Developing ASP.NET MVC Websites Targeting iPhone and other Mobile Phones

Read a good post this morning that used ActionFilters in ASP.NET MVC to help display specific views for iPhone Visitors.

The gist of the post is that you can detect the user agent of a request with an action filter and then based on that user agent switch the view at runtime. In this case the author use a MobileFilter that was placed on a Controller as such:

 

[MobileFilter]

public class HomeController : Controller

{

    /// <summary> 

    /// Shows the homepage. 

    /// </summary> 

    public ViewResult Index()

    {

        return View();

    }

}

 

with the ActionFilter looking like:

 

public override void OnActionExecuted(ActionExecutedContext filterContext

  // Only process when request is from mobile Safari 

  if (!IsMobileSafari(filterContext.RequestContext.HttpContext)) return

 

  // Only process Views 

  if (filterContext.Result.GetType() != typeof (ViewResult)) return

 

  // Get the name of the view 

  var viewName = GetViewName(filterContext); 

 

  var mobileViewName = viewName + ".iPhone"

 

  // Ensure that a mobile view has been defined 

  if (!ViewExists(mobileViewName, filterContext)) return

 

  // Assign the new mobile view 

  var result = (ViewResult)filterContext.Result

  result.ViewName = mobileViewName

 

 

Custom IViewEngine to Display Custom Views for iPhone and Mobile Phone Users

Another way of tackling this problem of targeting specific views for iPhone and other Mobile Phones that seems a bit better IMHO is via a custom view engine. Rather than having to use ActionFilters and adding ActionFilterAttributes on your ASP.NET MVC Controllers, you can instead use a custom view engine that does the same thing as the filter mentioned above: detect the user agent and display a custom view if it exists ( or the default one if it does not ).

I recommend checking out two resources for this solution:

 

My team has been using the custom view engine approach similar to above to target iPhone Users of our ASP.NET MVC Web Applications very successfully to date. That being said, I enjoyed the post mentioned above as it shows you the wonderful extensibility of the ASP.NET MVC Framework and how you can achieve a solution at a number of levels and extension points!!

 

David Hayden

 

ASP.NET MVC Tutorials

 

posted on Wednesday, July 29, 2009 11:25 AM

Main

News

Green Tea

.NET Development

Enterprise Library

Patterns & Practices