我在_Layout.cshtml中有脚本部分:
<html>
<body>
...
@RenderSection("FooterScript", required: false)
</body>
</html>
我查看了包含@Html.RenderPartial("LinksBlock", someModel)
的“Index.cshtml”。
LinksBlock部分需要脚本文件“links.js”。我想从我的局部视图中将links.js包含到FooterScript中,而不是从主视图(主视图不知道部分视图的依赖关系),我想确定,如果我在我的中使用多个LinksBlock查看,只包含1个links.js。有可能吗?
答案 0 :(得分:14)
部分不适用于部分视图。但是你可以编写一对可以结合使用的自定义助手:
public static class HtmlExtensions
{
public static IHtmlString RegisteredScripts(this HtmlHelper htmlHelper)
{
var ctx = htmlHelper.ViewContext.HttpContext;
var registeredScripts = ctx.Items["_scripts_"] as Stack<string>;
if (registeredScripts == null || registeredScripts.Count < 1)
{
return null;
}
var sb = new StringBuilder();
foreach (var script in registeredScripts)
{
var scriptBuilder = new TagBuilder("script");
scriptBuilder.Attributes["type"] = "text/javascript";
scriptBuilder.Attributes["src"] = script;
sb.AppendLine(scriptBuilder.ToString(TagRenderMode.Normal));
}
return new HtmlString(sb.ToString());
}
public static void RegisterScript(this HtmlHelper htmlHelper, string script)
{
var ctx = htmlHelper.ViewContext.HttpContext;
var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);
var registeredScripts = ctx.Items["_scripts_"] as Stack<string>;
if (registeredScripts == null)
{
registeredScripts = new Stack<string>();
ctx.Items["_scripts_"] = registeredScripts;
}
var src = urlHelper.Content(script);
if (!registeredScripts.Contains(src))
{
registeredScripts.Push(src);
}
}
}
然后在_Layout.cshtml
:
@Html.RegisteredScripts()
和你的部分:
@{Html.RegisterScript("~/scripts/foo.js");}