【发布时间】:2020-10-06 02:27:02
【问题描述】:
从部分角度来看,我想包含脚本或样式并将它们呈现到页眉或页脚(而不是内联)中,因此当我在 htmlextensions 中使用 TempData 时,我有一个 taghelper 和 htmlextension,但如果我使用ViewData,它不起作用。任何想法为什么?
部分观点:
<style asp-resource-location="Header">
.partial1 {
background-color: red;
}
</style>
<h2>Test Partial</h2>
<script asp-resource-location="Footer">
alert("Partial1");
</script>
Htmlextensions:
public static IHtmlContent InlineScripts(this IHtmlHelper html, Enums.ResourceLocation location)
{
var result = new StringBuilder();
var scripts = html.ViewData.ContainsKey(location.ToString()) ? html.ViewData[location.ToString()] as List<string> : new List<string>();
foreach (var script in scripts)
{
result.Append(script);
}
var tag = new TagBuilder(location == Enums.ResourceLocation.Header ? "style" : "script");
tag.InnerHtml.SetHtmlContent(result.ToString());
return tag;
}
public static void AddInlineScriptParts(this IHtmlHelper html, Enums.ResourceLocation location, string script)
{
var scripts = html.ViewData.ContainsKey(location.ToString()) ? html.ViewData[location.ToString()] as List<string> : new List<string>();
scripts.Add(script);
html.ViewData[location.ToString()] = scripts;
}
布局页面:
@Html.InlineScripts(Enums.ResourceLocation.Header)
样式标记助手:
public override void Process(TagHelperContext context, TagHelperOutput output)
{
if (Location != Enums.ResourceLocation.Header)
return;
var viewContextAware = _htmlHelper as IViewContextAware;
viewContextAware?.Contextualize(ViewContext);
var style = output.GetChildContentAsync().Result.GetContent();
_htmlHelper.AddInlineScriptParts(Location, style);
output.SuppressOutput();
}
【问题讨论】:
标签: asp.net-core razor