2012-07-09 38 views
4

在MVC 4中,您可以將.Mobile添加到任何視圖,移動設備將自動從相同的控制器獲取該視圖。有沒有辦法將.Mobile文件存儲在不同的文件夾中?我真的想將桌面文件存儲在一個「區域」中,而手機存儲在另一個「區域」中。任何人都知道這樣的事情?如何把移動視圖與MVC4的另一個文件夾?

回答

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()); 
相關問題