2011-03-29 51 views
1

當前我正在開發一個較舊的ASP.NET MVC 1應用程序,以添加主題支持。我瀏覽過網頁,並且能夠構建自己的ViewEngine,它迄今爲止工作得很好。我的手只有一個問題。ASP.NET MVC 1的主題支持,獲取視圖主人名稱

我已經覆蓋以下方法WebFormViewEngine:

public override ViewEngineResult FindView(
    ControllerContext controllerContext, 
    string viewName, 
    string masterName, 
    bool useCache) 

在這種方法我設置的位置格式的主題支持。不幸的是,masterName參數始終爲空!所以我需要檢查

if (string.IsNullOrEmpty(masterName))  
    masterName = "Site"; 

總是由我自己來使發動機工作。但是,由於我有幾個主文件,只要視圖需要另一個主站而不是「站點」,該解決方案就很糟糕。 有沒有人知道,我怎樣才能在這個方法中獲得主視圖名稱?

回答

2

自己解決。大量的研發後,我發現下面的代碼段,這讓我:

private void RenderViewPage(ViewContext context, ViewPage page) 
      { 
       if (!String.IsNullOrEmpty(MasterPath)) { 
        page.MasterLocation = MasterPath; 
       } else { 
        if (sc.WIP.CarharttIMD.Common.Config.GetStringValue("Theme") != "Default") 
         page.PreInit += new EventHandler(page_PreInit); 
       } 

       page.ViewData = context.ViewData; 
       page.RenderView(context); 
      } 

void page_PreInit(object sender, EventArgs e) 
      { 
       ViewPage page = sender as ViewPage; 
       //test for Default theme path, and replace with current theme 
       string defaultthemepath = string.Format("{0}Content/Default", page.Request.ApplicationPath); 
       if (!string.IsNullOrEmpty(page.MasterPageFile) && !page.MasterPageFile.ToLower().StartsWith(defaultthemepath.ToLower())) 
       { 
        string masterPagePath = page.MasterPageFile; 
        int lastIndexOfSlash = masterPagePath.LastIndexOf('/'); 
        string masterPageName = masterPagePath.Substring(lastIndexOfSlash + 1, masterPagePath.Length - lastIndexOfSlash - 1); 
        string newMaster = string.Format(
         "~/Content/{0}/Views/Shared/{1}", 
         Common.Config.GetStringValue("Theme"), 
         masterPageName 
        ); 
        if (File.Exists(page.Server.MapPath(newMaster))) 
         page.MasterLocation = newMaster; 
       } 
      } 

只好子類WebViewForm和HANDELING在PreInit事件中的主文件。

1

解決了同樣的問題,但方法有點不同。

假設你有不同看法樹在主題文件夾中,那麼你必須從WebFormViewEngine派生類MyViewEngine設置:

base.MasterLocationFormats = new[] { 
         "~/Theme/Views/{1}/{0}.master", 
         "~/Theme/Views/Shared/{0}.master" 
        } 
       ).ToArray(); 

base.ViewLocationFormats = viewLocationFormats.Concat(
        new[] { 
         "~/Theme/Views/{1}/{0}.aspx", 
         "~/Theme/Views/Shared/{0}.aspx", 
        } 
       ).ToArray() 

和覆蓋方法:

protected override bool FileExists(ControllerContext controllerContext, string virtualPath) 
{ 
    return System.IO.File.Exists(controllerContext.HttpContext.Server.MapPath(virtualPath)); 
} 

在來自全球的Application_Start方法。 asax.cs文件加入:

System.Web.Mvc.ViewEngines.Engines.Clear(); 
System.Web.Mvc.ViewEngines.Engines.Add(new WebFormThemeViewEngine()); 
+0

謝謝,但我不能確定這將如何解決我的問題。我認爲我不能重寫引擎,因爲我需要編輯並移動大量文件以進行這些更改。 – 2011-03-29 20:38:17

1

另外,您很可能使用了一些我在這個答案中描述的技術:how to change the themes in asp.net mvc 2

這是對MVC3和剃鬚刀,但除了查看一切應該只是罰款在MVC 1爲好。

+0

謝謝,我爲內容文件夾做了非常類似的事情。 – 2011-03-31 15:05:06