How to put .Mobile in another folder with MVC4?

In MVC 4, you can simply add .Mobile to any view, and mobile devices will automatically receive this view from the same controller. Is there a way to save .Mobile files in a different folder? I really want to store the desktop files in one β€œArea” and the mobile device in another β€œArea”. Does anyone know something like this?

+4
source share
1 answer

This can be easily accomplished by creating a custom RazorViewEngine implementation and adding custom mappings to ViewLocationFormats. It's important to remember adding custom mappings to the top of the ViewLocationFormats array, as they are more specific than existing mappings.

namespace MobileViewsInMobileFolder.Utility { public class MyCustomViewEngine : RazorViewEngine { public MyCustomViewEngine() { List<string> existingViewLocationFormats = ViewLocationFormats.ToList(); //Folder Structure: Views\Home\Desktop and Views\Home\Mobile existingViewLocationFormats.Insert(0, "~/Views/{1}/Desktop/{0}.cshtml"); existingViewLocationFormats.Insert(0, "~/Views/{1}/Mobile/{0}.cshtml"); //Folder Structure: Views\Desktop\Home and Views\Mobile\Home existingViewLocationFormats.Insert(0, "~/Views/Desktop/{1}/{0}.cshtml"); existingViewLocationFormats.Insert(0, "~/Views/Mobile/{1}/{0}.cshtml"); ViewLocationFormats = existingViewLocationFormats.ToArray(); } } } 

And then be sure to add a custom view engine to Application_Start

 ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new MyCustomViewEngine()); 
+2
source

All Articles