Sitecore创建包含字段[]的项目

wil*_*iam 3 .net c# sitecore sitecore6

我想使用后面的代码为sitecore创建一个项目.

我找到了这段代码,它的工作原理非常好.

public void CreateItem(String itmName)
{
    //Again we need to handle security
    //In this example we just disable it
    using (new SecurityDisabler())
    {
        //First get the parent item from the master database
        Database masterDb = Sitecore.Configuration.Factory.GetDatabase("master");
        Item parentItem = masterDb.Items["/sitecore/content/SOHO/Settings/Metadata/Project"];


        //Now we need to get the template from which the item is created
        TemplateItem template = masterDb.GetTemplate("SOHO/Misc/Project");
        //Now we can add the new item as a child to the parent
        parentItem.Add(itmName, template);


        //We can now manipulate the fields and publish as in the previous example
    }
}
Run Code Online (Sandbox Code Playgroud)

但我也想填写这些字段.喜欢..

Item.Fields["test"].Value="testing";
Run Code Online (Sandbox Code Playgroud)

为此,我发现了如何编辑项目

public void AlterItem()
{
  //Use a security disabler to allow changes
  using (new Sitecore.SecurityModel.SecurityDisabler())
  {
    //You want to alter the item in the master database, so get the item from there
    Database db = Sitecore.Configuration.Factory.GetDatabase("master");
    Item item = db.Items["/sitecore/content/home"];


    //Begin editing
    item.Editing.BeginEdit();
    try
    {
      //perform the editing
      item.Fields["Title"].Value = "This value will be stored";
    }
    finally
    {
      //Close the editing state
      item.Editing.EndEdit();
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

但我不知道如何将这两件事结合起来.

我想到了两种方法.

方法1

抓住我创造IDItem那个.

我可以抓住NameName可能会重复.

方法2

在创建之前填写字段 Item

但那时..我再也不知道如何做那两种方法.

如果我能得到一些提示,我将不胜感激.

提前致谢.

Mar*_*lak 5

方法item.Add()返回创建的项目,因此您的代码应如下所示:

    Item newItem = parent.Add(itemName, template);
    newItem.Editing.BeginEdit();
    newItem.Fields["fieldName"].Value = "fieldValue";
    newItem.Editing.EndEdit();
Run Code Online (Sandbox Code Playgroud)

  • 你也可以这样做更多的错误证明:`using(new EditContext(newItem)){// change fields here}` (3认同)