Вопрос

I want to add some metadata to my modern Team Site.

I can achieve this by simply adding columns to the Site Pages library in the site contents.

Now I want to do the same thing programmatically using CSOM.

I use the following code for that purpose:

var pages = siteContext.Web.Lists.GetByTitle("Site Pages");
var fieldCreationInformation = new OfficeDevPnP.Core.Entities.FieldCreationInformation(fieldType)
{
    DisplayName = fieldName,
    InternalName = fieldName.Replace(" ", ""),
    AddToDefaultView = true,
    Required = false,
    Id = Guid.NewGuid()
};
pages.CreateField(fieldCreationInformation);

This works - the fields are getting added to the pages library, however they don't appear as the properties when I'm editing the page, unlike the columns added in the GUI.

Why? How can I add columns programmatically and see them as page properties?

Это было полезно?

Решение

For tasks like these, I highly recommend using PowerShell PnP. It's a fantastic, powerful and easy-to use PowerShell Module.

This is what you want to do in only 4 lines including Installation of the module:

Install-Module SharePointPnPPowerShellOnline
Connect-PnPOnline -Url https://tenant.sharepoint.com
$list = Get-PnPList -Identity "Site Pages"
Add-PnPField -List $list -Type Text -InternalName "Age" -DisplayName "Age" 

If you use PowerShell ISE or Visual Studio code - you get intellisense with autocomplete like so:

enter image description here

This is the result: enter image description here

Update: Adding field to the content type

You can also try adding existing field to the content type you need:

Add-PnPFieldToContentType -Field "Age" -ContentType " Wiki Page"

Другие советы

We can use the CSOM C# code to achieve it.

string siteUrl="https://tenant.sharepoint.com/sites/lz";
string userName = "lz@tenant.onmicrosoft.com";
string password = "xxx";

var securePassword = new SecureString();
foreach (char c in password.ToCharArray()) securePassword.AppendChar(c);
var ctx = new ClientContext(siteUrl);
ctx.Credentials = new SharePointOnlineCredentials(userName, securePassword);
List oList = ctx.Web.Lists.GetByTitle("Site Pages");

var schemaField = "<Field DisplayName='MyField' Type='Text' />";
Field oField = oList.Fields.AddFieldAsXml(schemaField, true, AddFieldOptions.DefaultValue | AddFieldOptions.AddToAllContentTypes);
ctx.ExecuteQuery();

More information:Creating fields using CSOM

Лицензировано под: CC-BY-SA с атрибуция
Не связан с sharepoint.stackexchange
scroll top