您可以做的一件事是创建一些 HtmlHelper 扩展方法,如下所示:
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
public static class ScriptBundleManager
{
private const string Key = "__ScriptBundleManager__";
/// <summary>
/// Call this method from your partials and register your script bundle.
/// </summary>
public static void Register(this HtmlHelper htmlHelper, string scriptBundleName)
{
//using a HashSet to avoid duplicate scripts.
HashSet<string> set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;
if (set == null)
{
set = new HashSet<string>();
htmlHelper.ViewContext.HttpContext.Items[Key] = set;
}
if (!set.Contains(scriptBundleName))
set.Add(scriptBundleName);
}
/// <summary>
/// In the bottom of your HTML document, most likely in the Layout file call this method.
/// </summary>
public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
{
HashSet<string> set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;
if (set != null)
return Scripts.Render(set.ToArray());
return MvcHtmlString.Empty;
}
}
从你的部分,你会像这样使用它:
@{Html.Register("~/bundles/script1.js");}
在您的布局文件中:
...
@Html.RenderScripts()
</body>
由于您的部分在布局文件结束之前运行,所有脚本包都将被注册并且它们将被安全地呈现。