Episerver - 为什么绕过财产制定者?

问题描述 投票:0回答:1

我发现块块属性设置器在块“生命周期”期间只被调用一次。如果来自内部呼叫

SetDefaultValues(ContentType contentType)

我对此进行了一些测试:

1.创建新块

[ContentType(DisplayName = "SetterTestsBlock", GUID = "43ca7e93-6982-4b95-b073-c42af6ad2315", Description = "")]
public class SetterTestsBlock : BlockData
{
  public virtual string SomeVirtualStringProperty
  {
    get => this.GetPropertyValue(t => t.SomeVirtualStringProperty);
    set { this.SetPropertyValue(t => t.SomeVirtualStringProperty, "Ahoj1"); }      
  }

  public string SomeStringProperty
  {
    get => this.GetPropertyValue(t => t.SomeStringProperty);
    set { this.SetPropertyValue(t => t.SomeStringProperty, "Ahoj2"); }    
  }

  public override void SetDefaultValues(ContentType contentType)
  {
    SomeVirtualStringProperty = "Čau1";
    SomeStringProperty = "Čau2";
  }
} 

结果是可以预料的:

enter image description here

2.再次创建新块

[ContentType(DisplayName = "SetterTestsBlock", GUID = "43ca7e93-6982-4b95-b073-c42af6ad2315", Description = "")]
public class SetterTestsBlock : BlockData
{
  public virtual string SomeVirtualStringProperty
  {
    get => this.GetPropertyValue(t => t.SomeVirtualStringProperty);
    //set { this.SetPropertyValue(t => t.SomeVirtualStringProperty, "Ahoj1"); }
    //set { }
    set { throw new Exception(); }
  }

  public string SomeStringProperty
  {
    get => this.GetPropertyValue(t => t.SomeStringProperty);
    //set { this.SetPropertyValue(t => t.SomeStringProperty, "Ahoj2"); }
    //set { }
    set { throw new Exception(); }
  }

  //public override void SetDefaultValues(ContentType contentType)
  //{
  //    SomeVirtualStringProperty = "Čau1";
  //    SomeStringProperty = "Čau2";
  //}
} 

这次结果也是可以预料的:

enter image description here

3.发布更改以阻止测试2

enter image description here

这个结果不是那么令人期待:

enter image description here

测试结论:

  1. 在块首次创建期间,(仅)从SetDefaultValues(ContentType contentType)方法调用属性设置器。
  2. 永远不会进一步调用属性设置器。
  3. 观察到的行为不依赖于属性虚拟(虚拟修饰符)。

问题

想象下面的代码所示的情况。

[ContentType(DisplayName = "RealUsageSimulation", GUID = "12737925-ab51-4f63-9144-cd4632244a1c", Description = "")]
public class RealUsageSimulation : BlockData
{
  public string SomeStrPropWithDependency
  {
    get => this.GetPropertyValue(t => t.SomeStrPropWithDependency);
    set
    {
      this.SetPropertyValue(t => t.SomeStrPropWithDependency, GetDBValue());

      string GetDBValue()
      {  
      return string.Join(
        ",",
        value.Split(new[] { ',', ';', '/'}, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim()));
      }
    }
  }
}

由于测试中描述的问题,这段代码没用。

我错了吗?如何以一种良好的方式解决这个问题?

(我知道解决方案。我只是想知道细节,提示。)

episerver
1个回答
2
投票

例如,通过在编辑模式下编辑来保存内容时,属性值不会通过模型类的属性保存(请记住:即使从代码中删除了内容类型类,也可以保存内容)。

SetDefaultValues中调用setter的原因是因为你的代码使用了class属性。

对于您的情况,可能更适合连接ContentSaving事件以在保存内容时更改任何属性值。

© www.soinside.com 2019 - 2024. All rights reserved.