如何将.Mobile视图放在MVC4的另一个文件夹中?

时间:2012-07-09 21:38:43

标签: c# asp.net asp.net-mvc mobile asp.net-mvc-4

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

1 个答案:

答案 0 :(得分: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());