1

I'm writing an MVC web application, and some of the JavaScript files really only need to be "included" in specific views.

Retrieving a list of the bundle items I need has been achieved, using the following code:

        HttpContext currentHttpContext = HttpContext.Current;
        var httpContext = new HttpContextWrapper(currentHttpContext);

        BundleContext bundlecontext = new BundleContext(httpContext, BundleTable.Bundles, "~/bundles/");

        bundlecontext.EnableInstrumentation = false;

        var bundleList = bundlecontext.BundleCollection.ToList().Where(b => b.Path.StartsWith("~/bundles/" + HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString().ToLower() + "_"));

Outputting the contents of each file, or just doing a <script src="[file]"></script> is fairly trivial, however, what I'm trying to output is the same as what Script.Render() outputs:

<script src="/bundles/bootstrap?v=2Fz3B0iizV2NnnamQFrx-NbYJNTFeBJ2GM05SilbtQU1"></script>

Is it possible to do this programmatically?

1 Answer 1

2

I've figured this out, after looking at the source code for MVC I can see that you can just use Scripts.Render... which should have been obvious from the start >_<

    public static IHtmlString RenderScripts()
    {

        List<string> bundlePaths = new List<string>();
        HttpContext currentHttpContext = HttpContext.Current;
        var httpContext = new HttpContextWrapper(currentHttpContext);

        BundleContext bundlecontext = new BundleContext(httpContext, BundleTable.Bundles, "~/bundles/");

        bundlecontext.EnableInstrumentation = false;

        var bundleList = bundlecontext.BundleCollection.ToList().Where(b => b.Path.StartsWith("~/bundles/" + HttpContext.Current.Request.RequestContext.RouteData.Values["controller"].ToString().ToLower() + "_"));

        foreach (Bundle bundleItem in bundleList)
        {
            bundlePaths.Add(bundleItem.Path);
        }

        return Scripts.Render(bundlePaths.ToArray());
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.