如何在用户控件中包含ScriptBundle?

时间:2012-12-28 21:05:00

标签: asp.net-mvc asp.net-optimization

我有一些遗留的ASP.NET WebForms代码,它在继承自UserControl的类中使用RegisterClientScriptInclude。我想用一个新的Bundle替换对RegisterClientScriptInclude的多次调用。如何从编译程序集内部的bundle路由中解析bundle URL?

2 个答案:

答案 0 :(得分:1)

假设您已经注册了捆绑包,只想生成捆绑包的引用。

简单的方法就是打电话

BundleCollection.ResolveBundleUrl(<path to bundle, i.e. "~/bundles/mybundle">).  

注意,如果不使用Scripts帮助程序来呈现标记,您将始终获得对该包的引用,当您直接调用ResolveBundleUrl时,将不会有自动非包功能。

答案 1 :(得分:0)

试试这个方法:

private void RegisterJavaScriptBundle(string bundleIdent)
    {
        var bundleUrl = String.Format("~/bundles/{0}", bundleIdent);

        var name = String.Format("Bundle{0}", bundleIdent);

        if (ScriptManager.ScriptResourceMapping.GetDefinition(name) == null)
            ScriptManager.ScriptResourceMapping.AddDefinition(name, new ScriptResourceDefinition { Path = bundleUrl });

        ScriptManager.RegisterNamedClientScriptResource(this.Page, name);
    }

在usercontrol的load事件中调用它:

this.RegisterJavaScriptBundle("MyBundle");

这将生成对具有内容哈希的脚本的引用:

<script src="/bundles/MyBundle?v=B6mdgLTYJ2gPQv_XxE07ACAAaNA6Lo4L_KxViWZE-CY1" type="text/javascript"></script>