2012-11-18 20 views
1

寫作概念應用的一小證明,不知道爲什麼masterPath參數爲空:爲什麼CreateView中的masterPath參數爲空?

中的Application_Start

ViewEngines.Engines.Add(new AlternateLocationViewEngine(
       new string[] { 
        "~/Views/Shared/_Layout.cshtml", //Is this correct? Can/should i do that 
        "~/Views/Shared/{0}.cshtml", 
        "~/Plugins/Views/Shared/{0}.cshtml", 
       }, 
       new string[] { 
        "~/Plugins/Views/{1}/{0}.cshtml", 
        "~/Plugins/{1}/{0}.chstml",  
        "~/Plugins/Views/Shared/{0}.cshtml" 
       } 
      )); 




public class AlternateLocationViewEngine : RazorViewEngine 
    { 
     public AlternateLocationViewEngine(string[] masterLocations, string[] viewLocations) 
      : base() 
     { 
      MasterLocationFormats = masterLocations; 
      ViewLocationFormats = viewLocations; 
      PartialViewLocationFormats = ViewLocationFormats; 

     } 

     protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath) 
     { 
      if (string.IsNullOrEmpty(masterPath)) 
      {    
       masterPath = MasterLocationFormats.ElementAt(0); 
      } 


      var nameSpace = controllerContext.Controller.GetType().Namespace; 
      return base.CreateView(controllerContext, viewPath.Replace("%1", nameSpace), masterPath.Replace("%1", nameSpace)); 
     } 
    } 

正如你看到的我是被迫檢查masterPath是在方法CreateView的空() 。爲什麼是這樣?我錯過了一些基本的東西?

我的開發環境:ASP.NET MVC3,剃鬚刀,.NET4

+0

下面的代碼對於爲什麼masterPath是空的有意義嗎? – barry

回答

1

的masterPath創建與masterName一個的ViewResult時只會有一個值。

protected internal ViewResult View(string viewName, string masterName); 

在內部,RazorView在它的構造函數中處理空主路徑。

// where layoutPath is the masterPath arg from the RazorViewEngine's CreateView 
LayoutPath = layoutPath ?? String.Empty; 

當渲染視圖時,RazorView會將OverridenLayoutPath設置爲masterPath(如果提供)。

// An overriden master layout might have been specified when the ViewActionResult got returned. 
// We need to hold on to it so that we can set it on the inner page once it has executed. 
webViewPage.OverridenLayoutPath = LayoutPath; 

您不需要指定_Layout作爲MasterLocationFormat之一。以下是RazorViewEngine的默認行爲。

MasterLocationFormats = new[] { 
      "~/Views/{1}/{0}.cshtml", 
      "~/Views/{1}/{0}.vbhtml", 
      "~/Views/Shared/{0}.cshtml", 
      "~/Views/Shared/{0}.vbhtml" 
     }; 

您可以結算source code獲取更多靈感。