ASP.NET MVC 實現多模版的方法


需要解決的場景:

 

不用的場景下使用不用的mvc 模版。

 

目錄結構希望是

/templates

     Default

     Blue

     Red 

     .....

 

當傳入 “Blue” 參數的時候則調用 Blue 下面的View

 

查看 return View().. 的參數,發現可以指定 一個 IView 。

然后就有如下的代碼。

            RazorView rv = new RazorView(this.ControllerContext, "~/tempate/Blue/???.cshtml", null, true, new string[] { ".cshtml", ".vbcshtml" });

            return View(rv); 

 

然后,就解決了路徑的問題。

 

執行,出錯,不是正確的頁面文件。

 

這個錯誤解決方法很簡單(但也浪費了我不少時間):

把 /Views 下面的 web.config 拷貝到 /templates 下 

 

 

更好一點的解決方法:

 

自己實現一個 IView。

 

  1 using System;

 2  using System.IO;
 3  using System.Web.Compilation;
 4  using System.Web.Mvc;
 5  using System.Web.WebPages;
 6 
 7  namespace System.Web.Mvc
 8 {
 9      public  class ThemeRazorView : IView
10     {
11          private  string template;   //模版的目錄名稱 
12 
13          public ThemeRazorView( string _template)
14         {
15              this.template = _template;
16         }
17 
18          public  void Render(ViewContext viewContext, TextWriter writer)
19         {
20              // 這個地方可以自己實現,或者從 web.config 里讀取,或者從用戶選擇的模版中讀取
21               if (template.IsNullOrEmpty())
22             {
23                 template =  " Default ";
24             }
25              string viewPath =  " ~/templates/ " + template +  " / " + viewContext.RouteData.GetRequiredString( " controller ") +  " / " + viewContext.RouteData.GetRequiredString( " action ") +  " .cshtml ";
26 
27             Type viewType = BuildManager.GetCompiledType(viewPath);
28              var page = Activator.CreateInstance(viewType)  as WebViewPage;
29            
30             page.VirtualPath = viewPath;
31             page.ViewContext = viewContext;
32             page.ViewData = viewContext.ViewData;
33             page.InitHelpers();
34 
35             WebPageContext pageContext =  new WebPageContext(viewContext.HttpContext,  nullnull);
36             WebPageRenderingBase startPage = StartPage.GetStartPage(page,  " _ViewStart "new  string[] {  " cshtml "" vbhtml " });
37 
38             page.ExecutePageHierarchy(pageContext, writer, startPage);
39         }
40 
41     }
42 }

 

 

完成。

 

 現在調用方法為:

            return View(new ThemeRazorView("Blue")); 

 


 

 參考了:http://www.cnblogs.com/artech/archive/2012/04/10/how-mvc-works.html  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM