您可以构建一个 html 扩展功能,像这样
/// <summary>
/// This section is for adding a script to the <head> tag from a partial view (or any other place)
/// </summary>
private const string SCRIPTBLOCK_BUILDER = "_ScriptBlockBuilder_";
public static MvcHtmlString Script(this HtmlHelper htmlHelper, Func<object, HelperResult> template)
{
htmlHelper.ViewContext.HttpContext.Items[SCRIPTBLOCK_BUILDER + Guid.NewGuid()] = template;
return MvcHtmlString.Empty;
}
public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
{
foreach (object key in htmlHelper.ViewContext.HttpContext.Items.Keys)
{
if (key.ToString().StartsWith(SCRIPTBLOCK_BUILDER))
{
var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
if (template != null)
{
htmlHelper.ViewContext.Writer.Write(template(null));
}
}
}
return MvcHtmlString.Empty;
}
然后就可以使用这两个功能了。在您的 _Layout.cshtml 中,您放置@Html.RenderScripts()
了要呈现所有脚本的位置。
然后像这样将所有脚本包装在视图中
@Html.Script(
@<script type="text/javascript">
// Your scripts
</script>
)