【问题标题】:Accessing ViewData in Layout for page with partial view not working在部分视图不起作用的页面的布局中访问 ViewData
【发布时间】: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


    【解决方案1】:

    我使用了 ViewContext.HttpContext.Items 并且它有效。我认为它会比使用会话的 TempData 更好。如果有人有任何理由我不应该使用它,请告诉我。如果有人知道为什么 ViewData 不起作用,我也很想知道。

    【讨论】:

      猜你喜欢
      • 2019-03-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-18
      • 2013-11-09
      相关资源
      最近更新 更多