4

在 MVC 4 中,您只需将 .Mobile 附加到任何视图,移动设备将自动从同一控制器获取该视图。有没有办法将 .Mobile 文件存储在不同的文件夹中?我真的很想将桌面文件存储在一个“区域”中,而将移动设备存储在另一个“区域”中。有人知道这样的事情吗?

4

1 回答 1

2

这可以通过创建 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 中添加自定义视图引擎

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyCustomViewEngine());
于 2012-07-16T12:20:20.760 回答