【问题标题】:Sitecore How to check if an Item has a certain fieldSitecore 如何检查一个项目是否有某个字段
【发布时间】:2016-02-01 21:58:21
【问题描述】:

对于站点核心项目testItem,我如何确保该项目具有“Title”字段。

我问是因为我正在以编程方式在项目的模板中创建一些字段。因此,如果字段已经存在,则不应再次创建它。

因为有了这段代码,我可以知道该字段是否有一些价值。

testItem["Title"] 
testItem.Fields["Title"] 

【问题讨论】:

  • 只检查空。它只是一个集合。
  • 如果字段Title存在但包含null怎么办?
  • 那么它不会为空,但它的.Value 将是
  • 是否要将继承的字段视为属于当前模板?例如,如果当前模板没有“标题”,但父模板有,您希望发生什么?

标签: c# sitecore sitecore7.2


【解决方案1】:

请检查此代码,您正在检查项目、字段集合和字段值是否为空

if(testItem!= null && testItem.Fields != null && testItem.Fields["Value"] != null)
{
  string name = testItem.Fields["Title"].Value;
}

【讨论】:

  • .. 或使用一些 C#6 空传播魔法 :) var value = item?.Fields["Title"]?.Value;
【解决方案2】:

以下代码将返回值,包括字段的标准或默认值:

        if (testItem.Fields["Title"] != null && testItem.Fields["Title"].HasValue)
        {
            string title = testItem["Title"].Value;
        }

【讨论】:

    【解决方案3】:

    为了避免多次检查您的 testItem 字段,您可以强制转换为一个字段,然后:检查该字段是否为空,它有一个值,然后检索该值。

    这里的好处是,如果您需要在多个地方访问该字段,您不必每次都从 testItem 中检索。

    例如

    Field titleField = testItem.Fields["Title"];
    
    if (titleField != null && titleField.HasValue)
    {
        //do something with value
        string fieldValue1 = titleField.Value;
    
        //or (see intellisense for params)
        string fieldValue2 = titleField.GetValue(true);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-16
      • 1970-01-01
      • 1970-01-01
      • 2019-08-08
      • 1970-01-01
      相关资源
      最近更新 更多