使用CSOM以编程方式在SharePoint中创建字段(不使用XML)

时间:2016-01-07 14:38:38

标签: sharepoint csom

是否可以使用CSOM在SharePoint中创建字段,而不是使用XML?

我见过很多使用XML的例子,但没有一个只是以编程方式为字段设置属性?

fields.Add(new **FieldCreationInformation** {
    InternalName = "Test",
   etc..
});

2 个答案:

答案 0 :(得分:3)

这是可行的,在下面的例子中引入了FieldCreationInformation class

[XmlRoot("Field")]
public class FieldCreationInformation
{
    [XmlAttribute("ID")]
    public Guid Id { get; set; }

    [XmlAttribute()]
    public string DisplayName { get; set; }

    [XmlAttribute("Name")]
    public string InternalName { get; set; }

    [XmlIgnore()]
    public bool AddToDefaultView { get; set; }


    //public IEnumerable<KeyValuePair<string, string>> AdditionalAttributes { get; set; }

    [XmlAttribute("Type")]
    public FieldType FieldType { get; set; }

    [XmlAttribute()]
    public string Group { get; set; }

    [XmlAttribute()]
    public bool Required { get; set; }


    public string ToXml()
    {
        var serializer = new XmlSerializer(GetType());
        var settings = new XmlWriterSettings();
        settings.Indent = true;
        settings.OmitXmlDeclaration = true;
        var emptyNamepsaces = new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty });

        using (var stream = new StringWriter())
        using (var writer = XmlWriter.Create(stream, settings))
        {
            serializer.Serialize(writer, this, emptyNamepsaces);
            return stream.ToString();
        }
    }



    public FieldCreationInformation()
    {
        Id = Guid.NewGuid();
    }

}

然后创建新字段的扩展方法:

public static class FieldCollectionExtensions
{
    public static Field Add(this FieldCollection fields, FieldCreationInformation info)
    {
        var fieldSchema = info.ToXml();
        return fields.AddFieldAsXml(fieldSchema, info.AddToDefaultView, AddFieldOptions.AddFieldToDefaultView);
    }
}

<强>用法

var fieldInfo = new FieldCreationInformation();
fieldInfo.FieldType = FieldType.Geolocation;
fieldInfo.InternalName = "ContactsLocation";
fieldInfo.DisplayName = "Contacts Location";
ctx.Site.RootWeb.Fields.Add(fieldInfo);
ctx.ExecuteQuery();

答案 1 :(得分:0)

当我使用CSOM / JSOM添加字段时,我使用FieldCollection AddFieldAsXml上的方法。这需要您构建一个包含所需字段的所有属性的xml字符串,但它可以工作。我在下面列出了相关cpde的摘录:

Microsoft.SharePoint.Client.Web web = _context.Web;
FieldCollection fields = web.Fields;
_context.Load(fields);
_context.ExecuteQuery();

Field field = fields.FirstOrDefault(f => f.StaticName == _staticName);

if (field == null)
{
    Field createdField = fields.AddFieldAsXml(xml, false, AddFieldOptions.AddToNoContentType);
    _context.Load(createdField);
    _context.ExecuteQuery();

}

如果要将字段直接添加到现有列表,则使用类似的代码。