在 MVC 4 中,您只需将 .Mobile 附加到任何 View ,移动设备将自动从同一个 Controller 获得该 View 。有没有办法将 .Mobile 文件存储在不同的文件夹中?我真的很想将桌面文件存储在一个“区域”中,而将移动设备存储在另一个“区域”中。有人知道这样的事情吗?
最佳答案
这可以通过创建 RazorViewEngine 的自定义实现并将自定义映射添加到 ViewLocationFormats 来轻松完成。请务必记住将自定义映射添加到 ViewLocationFormats 数组的开头,因为它们比现有映射更具体。
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();
}
}
}
然后确保在 Application_Start 中添加自定义 View 引擎
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyCustomViewEngine());