重现Script.Render()以在MVC中输出特定于视图的脚本

时间:2014-08-19 15:09:23

标签: c# asp.net-mvc asp.net-mvc-4

我正在编写一个MVC Web应用程序,并且一些JavaScript文件实际上只需要“包含”在特定视图中。

使用以下代码检索我需要的包项目列表:

        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() + "_"));

输出每个文件的内容,或只是执行< script src =“[file]”>< / script>但是,我想要输出的内容与Script.Render()输出的内容相同:

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

是否可以通过编程方式执行此操作?

1 个答案:

答案 0 :(得分:2)

' ave想出了这一点,在查看了MVC的源代码后,我可以看到你可以使用Scripts.Render ......从开始就应该是显而易见的><

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