ASP.NET MVC BundleConfig, scripts returning an empty response?

Sam Rueby .NET Tips, Web Development 2 Comments

The Visual Studio template for ASP.NET MVC 5 comes with Microsoft.AspNet.Web.Optimization, which is used in  BundleConfig they provide you. I haven’t used this much and wanted to try it. I wiped out the default stuff and included a line for the only script I needed.

Looks great, follows the same pattern as their example. And then in your view (probably your _Layout.cshtml) you have:

Cool. The keys match, it’s one script, there’s no way this can go wrong.

And it doesn’t! If you’re debugging. Works great.

But then if you turn on optimizations, either by setting debug=false in the Web.Config or by specifying  BundleTable.EnableOptimizations = true;  manually in the web config, the script isn’t included in the page.

Note to self: always test in release mode before publishing.

What went wrong? I check out the markup:

Okay- looks great. I click on it: totally blank. Nothing. Content length: 0.

Fast forward. It turns out

that if the key you’re using for your bundle, in this case “~/scripts”, matches the virtual path of the file included in the bundle, then it will not be included. To fix this, I changed the key to “~/bundles/scripts” and everything is happy now.

  • Thank you so much!, you’ve saved a lot of time.

  • hatetoregister

    FYI – This is by design. That last parameter in the bundle virtual path is just a key in case you have multiple scripts in the same directory and you want to pull them. It allows you to have something like this

    bundles.Add( new ScriptBundle( “~/scripts/number1” ).Include( “~/scripts/MyHappyScript1.js”

    bundles.Add( new ScriptBundle( “~/scripts/number2” ).Include( “~/scripts/MyHappyScript2.js”

    You might ask why you would want to do this instead of bundling everything.
    This can be used if you want to place scripts in different areas in your website.
    For example, if you need to put one before the fold and one after.
    If you couldn’t specify that additional parameter, you would have

    bundles.Add( new ScriptBundle( “~/scripts” ).Include( “~/scripts/MyHappyScript1.js”

    bundles.Add( new ScriptBundle( “~/scripts” ).Include( “~/scripts/MyHappyScript2.js”

    which would create a problem when you went to reference the scripts in a view.

    How would you know which one, MyHappyScript1 or MyHappyScript2, you were trying to reference?

    This is why that last parameter is used and it can be anything you want it to be.

    Also, please know that if you have a folder that is deeper than Scripts, you STILL apply the last parameter and call it whatever you want. For example, if you were referencing a css folder in the Content folder, you would do it like this-

    bundles.Add( new StyleBundle( “~/Content/css/myFileKey1” ).Include( “~/Content/css/MyHappyStyle1.js”