有時候,我們的項目涉及到多種風格,我們可以通過擴展RazorViewEngine,這樣就可以保持後臺代碼不發生變化。 新建類ThemeViewEngine繼承於RazorViewEngine Global類中,註冊這種引擎 web.config配置具體風格: 項目文件結構: View: Americ ...
有時候,我們的項目涉及到多種風格,我們可以通過擴展RazorViewEngine,這樣就可以保持後臺代碼不發生變化。
新建類ThemeViewEngine繼承於RazorViewEngine
1 public class ThemeViewEngine : RazorViewEngine 2 { 3 public ThemeViewEngine(string theme) 4 { 5 ViewLocationFormats = new[] 6 { 7 "~/Views/Themes/" + theme + "/{1}/{0}.cshtml", 8 "~/Views/Themes/" + theme + "/Shared/{0}.cshtml" 9 }; 10 11 PartialViewLocationFormats = new[] 12 { 13 "~/Views/Themes/" + theme + "/{1}/{0}.cshtml", 14 "~/Views/Themes/" + theme + "/Shared/{0}.cshtml" 15 }; 16 17 AreaViewLocationFormats = new[] 18 { 19 "~Areas/{2}/Views/Themes/" + theme + "/{1}/{0}.cshtml", 20 "~Areas/{2}/Views/Themes/" + theme + "/Shared/{0}.cshtml" 21 }; 22 23 AreaPartialViewLocationFormats = new[] 24 { 25 "~Areas/{2}/Views/Themes/" + theme + "/{1}/{0}.cshtml", 26 "~Areas/{2}/Views/Themes/" + theme + "/Shared/{0}.cshtml" 27 }; 28 } 29 }
Global類中,註冊這種引擎
1 //不同風格 2 if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["Theme"])) 3 { 4 var activeTheme = ConfigurationManager.AppSettings["Theme"]; 5 ViewEngines.Engines.Insert(0, new ThemeViewEngine(activeTheme)); 6 }
web.config配置具體風格:
1 <add key="Theme" value="China" />
項目文件結構:
View:
America:
1 @{ 2 ViewBag.Title = "ShowTheme"; 3 } 4 5 <h2>ShowTheme America</h2>
China:
1 @{ 2 ViewBag.Title = "ShowTheme"; 3 } 4 5 <h2>ShowTheme China</h2>
運行:
1 public ActionResult ShowTheme() 2 { 3 return View(); 4 }
效果圖: