2014-02-27 28 views
0

您是否有任何人知道爲什麼Script.Render沒有禁用編譯的bundle debug =「true」不是相對於根文件夾Script.Render(絕對路徑或部分路徑)未禁用編譯綁定debug = true

我創建使用像根目錄的相對路徑管束(此路徑類型是強制性的,否則將引發異常):

Bundle jsBundle = new ScriptBundle("~/bundles/myscripts/"); 

但是,當我嘗試呈現它,我需要提供完整的網址,如下所示:

Scripts.Render("http://myserver/bundles/myscripts/") 

而且的束不論編譯調試模式啓用。

任何想法我失蹤?

我的問題與this question非常相關 - 我正在渲染我的包 - 現在:編譯debug =「true」時如何禁用它?

任何想法?

謝謝! 的Ovi

+0

當您嘗試提供相對路徑時,您的代碼是什麼? – binard

+0

嗨jbbi,當我在Application_Start中創建包時,是從問題開始的第一行代碼,當我嘗試渲染它時,就像'<%:Scripts.Render(「protocol:// myserver/bundles/vxscripts /」 )%>'。我使用這種語法,因爲這個包通過e CDN,我需要完整的URL。 –

+0

但無論如何,一旦我在Scripts.Render中不使用〜字符,就無法使用編譯調試模式禁用該包。這是我的問題,如何自定義此行爲以便能夠使用路徑的部分路徑或完整URL,並仍然使用編譯調試模式來決定是否啓用綁定。 –

回答

1

要回答我自己的問題:Scripts.Render不切換依賴於編譯模式捆綁,如果束URL爲提供完整的URL:

Scripts.Render("http://myserver/bundles/myscripts/") 

我採取的方法是創建我自己的mvc幫手來渲染包:

public MvcHtmlString BundleScript(string bundleUrl) 
{ 
     var javascriptBuilder = new StringBuilder(); 
     bool filesExist = false; 
     bool isDynamicEnabled = IsDynamicEnabled(); 

     if (!isDynamicEnabled) 
     { 
      IEnumerable<string> fileUrls = GetBundleFilesCollection(bundleUrl); 
      string rootVirtualDirectory = "~/content/js/"; 

      if (fileUrls != null) 
      { 
       foreach (string fileUrl in fileUrls) 
       { 
        javascriptBuilder.Append(new ScriptTag().WithSource(GetScriptName(fileUrl, rootVirtualDirectory)).ToHtmlString()); 
       } 
       filesExist = true; 
      } 
     } 

     if (isDynamicEnabled || !filesExist) 
     { 
      javascriptBuilder.Append(new ScriptTag().WithSource(bundleUrl).ToHtmlString()); 
     } 
     return MvcHtmlString.Create(javascriptBuilder.ToString()); 
} 

private IEnumerable<string> GetBundleFilesCollection(string bundleVirtualPath) 
{ 
     var collection = new BundleCollection { BundleTable.Bundles.GetBundleFor(bundleVirtualPath) }; 
     var bundleResolver = new BundleResolver(collection); 
     return bundleResolver.GetBundleContents(bundleVirtualPath); 
} 

private bool IsDynamicEnabled() 
{ 
     return BundleTable.EnableOptimizations; 
} 
private static string GetScriptName(string scriptUrl, string virtualDirectory) 
{ 
     return scriptUrl.Replace(virtualDirectory, string.Empty); 
}