从局部视图剃刀部分夹杂物 [英] Razor section inclusions from partial view
问题描述
我有我的_Layout.cshtml脚本的一节:
I have section for scripts in my _Layout.cshtml:
<html>
<body>
...
@RenderSection("FooterScript", required: false)
</body>
</html>
我有看法Index.cshtml包含 @ Html.RenderPartial(LinksBlock,someModel)
。
LinksBlock部分需要脚本文件links.js。我要让links.js纳入FooterScript从我的部分观点,而不是从主视图(主视图不知道局部视图的依赖关系),我想可以肯定,如果我用1个多LinksBlock我看来,只有1 links.js被列入。这可能吗?
I have view "Index.cshtml" that contains @Html.RenderPartial("LinksBlock", someModel)
.
LinksBlock partial requires script file "links.js". I want to make links.js inclusion into FooterScript from my partial view, not from main view (main view don't know about dependencies of partial view), and I want to be sure, that if I use more than 1 LinksBlock in my view, only 1 links.js was included. Is it possible?
推荐答案
节不与局部视图工作。但是,你可以写一对定制的助手的,可以结合使用:
Sections do not work with partial views. But you could write a pair of custom helpers that could be used in conjunction:
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");}
这篇关于从局部视图剃刀部分夹杂物的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!