Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MVC4, how do I create a script bundle in a Razor file

I'm setting up my MVC4 app to use the built-in ASP.Net bundling (converting from Squishit). I've set up the BundleConfig class, and things all work fine, but for cases where a Razor file only has a reference to one JavaScript file, I don't see the need to involve that config file. I'd rather just add the script to the BundleTable right in my Razor 'Scripts' section, and Render it right there. That way I can do a release to production quite easily for small changes if I have to rather than change the BundleConfig file. This is what I have:

@section Scripts
{
    @{   
        const string bundle = "~/bundles/{myVirtualBundlePath}";
        BundleTable.Bundles.Add(new ScriptBundle(bundle)
            .Include("{myActualJavaScriptFilePath}"));
        Scripts.Render(bundle);
    }
}

and while this builds ok, the reference to that bundled file never gets output to HTML.

Do I need to get a reference to the particular BundleCollection that the BundleConfig uses?

like image 722
Ralph Lavelle Avatar asked Jan 16 '13 00:01

Ralph Lavelle


People also ask

How do I bundle a JavaScript file in .NET core?

In Task runner right-click or double click on update all files; after doing this your output file mentioned in bundleconfig,json will be created in a mentioned path as shown below. Output will be a file created like this if not please reload your project once. Add CSS and JS file to your . cshtml page or _layout page.

What are the types of files we can bundle in bundle config?

How to add files in BundleConfig. There you see two type of bundle class, StyleBundle and ScriptBundle , Now you can create as many instance as you need of any of those classes and the finally add to BundleCollection. remember BundleCollection class will reamin always one only.

HOW include script in Cshtml?

Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.


1 Answers

Only difference between mine (that works) is that I add the bundle outside of the script block. If this doesn't work make sure it does work in the main bundle start-up, it could be some other issue.

@{ BundleTable.Bundles.Add(new ScriptBundle("~/Scripts/Plugins/highcharts")
                           .Include("~/Scripts/Plugins/highcharts.js")); }
@section Scripts
{    
    @Scripts.Render("~/Scripts/Plugins/highcharts")
    @Scripts.Render("~/Scripts/Views/Charts/transportDelayCharts")
}
like image 93
GarethReid Avatar answered Nov 01 '22 18:11

GarethReid