Какая полезная нагрузка должна быть отправлена ​​для параметра "ViewFields" как часть использования SPO REST API?

Я пытаюсь создать представление списка SharePoint через REST API SharePoint с определенным набором столбцов, которые будут частью представления. Конечная точка, которую я использую, указана ниже:

POSTMAN API Запрос:

СПОСОБ HTTP: POST

URL: https://tenantname.sharepoint.com/sites/SPSite/_api/web/lists/getbytitle(%27ListName%27)/views Заголовки:

  • 'Принять' - 'application / json;odata=verbose'
  • 'Content-Type' - 'application / json;odata=verbose'

Тело (JSON):

{
"__metadata":{
    "type":"SP.View"
},
"Title":"TestView",
"ViewFields":["Title","Name"]
}

Я получаю сообщение об ошибке JSON, поскольку эта полезная нагрузка кажется неправильной. Нужна помощь в понимании того, как создать представление с определенными полями с помощью REST API SharePoint.

Спасибо, еш

1 ответ

Решение

При создании представления поддерживается добавление полей просмотра, это необходимо сделать после создания представления списка.

Поэтому сначала создайте такое представление:

var viewQuery = "<OrderBy><FieldRef Name=\"ID\" /></OrderBy>";
 
    $.ajax
        ({
            // _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
            // You can replace this with other site URL where you want to apply the function
 
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyList')/views",
            type: "POST",
 
            data: "{'__metadata':{'type': 'SP.View'},'ViewType': 'HTML','Title':'New View Created From REST','PersonalView':false,'ViewQuery':'" + viewQuery + "'}",
            headers:
               {
                   // Accept header: Specifies the format for response data from the server.
                   "Accept": "application/json;odata=verbose",
                   //Content-Type header: Specifies the format of the data that the client is sending to the server
                   "Content-Type": "application/json;odata=verbose",
                   // X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
                   "X-RequestDigest": $("#__REQUESTDIGEST").val()
               },
            success: function (data, status, xhr) {
                alert(data.d.Id);
            },
            error: function (xhr, status, error) {
                console.log("Failed");
            }
        });

Затем установите поле просмотра для вновь созданного представления списка следующим образом:

 $.ajax
        ({
            // _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
            // You can replace this with other site URL where you want to apply the function
 
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('MyList')/Views(guid'58cfaaa2-107c-4a94-8490-38d1df195e5b')/ViewFields/addviewfield('Created')",
            type: "POST",
            headers:
               {
                   // Accept header: Specifies the format for response data from the server.
                   "Accept": "application/json;odata=verbose",
                   //Content-Type header: Specifies the format of the data that the client is sending to the server
                   "Content-Type": "application/json;odata=verbose",
                   // X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
                   "X-RequestDigest": $("#__REQUESTDIGEST").val()
               },
            success: function (data, status, xhr) {
                console.log("Success");
            },
            error: function (xhr, status, error) {
                console.log("Failed");
            }
        });

Таким образом, в приведенном выше примере в viewFields добавляется поле "Создано", а View Guid предупреждает при первом запросе, используйте его во втором запросе.

Другие вопросы по тегам