Search code examples
asp.net-mvcoptimizationasp.net-mvc-4minifyasp.net-optimization

Using ASP.NET Javascript Bundles from the controller


I realise this breaks the MVC pattern, but there is a viable reason for doing it this way in an application I am currently building :)

What I am trying to do is output a JavaScript bundle directly from the Controller rather than via a link via a View.

So for example I have a bundle called "~/jQueryPlugin" what I'd like to do is something along the lines of

return this.JavaScript(BundleTable.GetBundle("~jQueryPlugin").BundleContent)"

However for the life of me I cannot figure out what the BundleTable.GetBundle("~jQueryPlugin").BundleContent part should be in order to get a string representation of the combined minimized bundle.

Any help would be appreciated·


Solution

  • In the 1.1-alpha1 release we added a new Optimizer class which should allow you to more easily do this. Its intended to be a standalone class that's useable out of side of ASP.NET hosting, so setting it up will be slightly different.

    You can get the bundle contents out via something like this:

            OptimizationSettings config = new OptimizationSettings() {
                ApplicationPath = "<your physical path to the app>",
                BundleSetupMethod = (bundles) => {
                    bundles.Add(new ScriptBundle("~/bundles/js").Include("~/scripts/jqueryPlugin.js"));
                }
            };
    
            BundleResponse response = Optimizer.BuildBundle("~/bundles/js", config);
            Assert.IsNotNull(response);
            Assert.AreEqual("<your bundle js contents>", response.Content);
            Assert.AreEqual(JsMinify.JsContentType, response.ContentType);
    

    The next release should be fleshing this scenario out more, as it is needed for build time bundling integration with Visual Studio.