Search code examples
c#asp.netasp.net-mvcsystem.web.optimization

Script.Render(absolute or partial path) is not disabling the bundling for compilation debug=true


Does any of you know why the Script.Render is not disabling the bundle for compilation debug ="true" when the bundle path is not relative to the root folder ?

I am creating the bundle using a relative path to the root like (this path type is mandatory, otherwise an exception will be thrown):

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

But when I try to render it I need to provide the full url like below:

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

And the bundle is enabled irrespective of compilation debug mode.

Any ideas what I am missing?

My question is very related to this question - I am rendering my bundle that way - now: how can I make it disabled when compilation debug="true" ?

Any ideas ?

Thanks! Ovi


Solution

  • To answer to my own question: Scripts.Render doesn't toggle the bundling depending on compilation mode if the bundle url is provided as full url like:

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

    The approach I took was to create my own mvc helper to render the bundle:

    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);
    }