【问题标题】:Getting all of the children Tag Helpers in a parent Tag Helper Asp.Net Core在父标签助手 Asp.Net Core 中获取所有子标签助手
【发布时间】:2017-07-03 14:46:26
【问题描述】:

我正在尝试编写两个标签助手,用于在剃刀视图中本地化字符串。父标签的目的是收集所有子标签请求的key,从数据库中批量获取并缓存。

然后子标签将使用缓存版本,这样我希望降低数据库的负载。我正在寻找这样的东西:

<parent-tag>
   <child-tag key="Hello" /> 
     some HTML here
   <child-tag key="Hi!" /> 
</parent-tag>

我希望能够在 Parent 标签的 Invoke 方法中获取对象列表。

我也尝试过storing data in TagHelperContext to communicate with other tag helpers,但这也不起作用,因为我必须在 Parent 的 Invoke 方法中调用 output.GetChildContentAsync(),这违背了缓存的全部目的。

【问题讨论】:

  • 那么是遍历children有问题还是你尝试了不同的方法?
  • @FarrukhSubhani 我知道的唯一遍历孩子的方法是调用output.GetChildContentAsync(),然后通过content.GetContent() 获取内容,但这种方法1.渲染(并因此调用)所有孩子标签助手,我不想要 2. 你必须使用字符串操作,这对性能非常不利
  • 我需要在不调用output.GetChildContentAsync()的情况下获取孩子的名单

标签: c# razor asp.net-core asp.net-core-tag-helpers


【解决方案1】:

@Encrypt0r 您可以拥有 TagHelpers context.Items 和本地化密钥的内存中静态缓存关系。这将涉及使用你的 context.Items 来执行 GetChildContentAsync 一次。所有后续时间都将通过根据 context.Items 查找键值来缓存(假设键值不是动态的)。

这样想:

// Inside your TagHelper
if (_cache.TryGetValue(context.UniqueId, out var localizationKeys))
{
    ... You already have the keys, do whatever
}
else
{
    var myStatefulObject = new SomeStatefulObject();
    context.Items[typeof(SomeStatefulObject)] = myStatefulObject;
    await output.GetChildContentAsync();
    _cache[context.UniqueId] = new LocalizationKeyStuff(myStatefulObject);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 2023-04-03
    • 2018-10-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    相关资源
    最近更新 更多