How Would I Change ASP.NET MVC Views Based on Device Type?

Viewed 11956

I'm working my way through some ASP.NET MVC reading and I have a web app at work that I'll be migrating from WebForms to MVC. One of the feature requests I expect to get in the process is to have a simplified view returned if the user is coming from a mobile device.

I can't quite see where the best place is to implement that type of logic. I'm sure there's a better way than adding an if/else for Browser.IsMobileDevice in every action that returns a view. What kind of options would I have to do this?

5 Answers

I think that the right place to plug this functionality is custom ViewEngine. But you should be aware of how IViewEngine.FindView method is called by the ViewEngineCollection (find more on this here).

Updated solution suggested by Scott Hanselman does not work correctly. You can find my sample implementation of this approach here. Check readme file that describes how you can repeat incorrect behavior.

I suggest another approach that checks if a view was not found by original ViewEngine and if useCache parameter is true, it checks if view exist in original ViewEngine with parameter useCache=false.

It is too complex to put all code here but you can find the suggested approach implemented in my open-source playground here. Check MobileViewEngine class and unit-tests.

Some MobileViewEngine features:

  • Works correctly with view caching and uses original view engine cache.
  • Supports both: shot view names and relative view paths (~/Views/Index) used by MvcContrib T4 template.
  • Resolves "Index" view as following:
    • Mobile/Platform/Index – if view exists and a mobile device platform (IPhone, Android etc.) is enlisted in supported list.
    • Mobile/Index - view for all other mobile devices. If the view does not exists you can optionally fallback to desktop view version.
    • Index – for desktop view version.
  • You can customize mobile view hierarchy (e.g. Mobile/ Platform/Manufacturer) or customize mobile view path resolution by adding/changing device rules (see MobileDeviceRule and PlatformSpecificRule).

Hope, this will help

Related