c# – 如何将.Mobile视图放入MVC4的另一个文件夹中?

在MVC 4中,您可以将.Mobile附加到任何视图,移动设备将自动从同一控制器获得该视图.有没有办法将.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中添加自定义视图引擎

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new MyCustomViewEngine());
点赞