Kendo UI Scheduler создать элемент SharePoint не удается.Недостающий тег метаданных - PullRequest
0 голосов
/ 27 ноября 2018

При использовании Kendo Scheduler для работы со списком SharePoint я могу отображать и редактировать элемент, но сталкиваюсь с проблемой добавления / создания нового элемента.Я не получаю ошибку javascript при сохранении элемента, но, выполнив функцию done в jquery, я получаю ошибку неверного запроса.

При редактировании записи в данных существует объект __metadata, но во время создания этот элемент отсутствует.Объект __metadata содержит URL-адрес и другую важную информацию.

Когда я форматирую вызов редактирования, данные выглядят так: "{\" __ metadata \ ": {\" id \ ": \" Web / Lists (guid'2abecf66-35ed-4c67-b1f1-8b7255ebf0e2)«) / Items (2) \», \ "URI \": \ "https: /// _ API / Web / Списки (guid'2abecf66-35ed-4c67-b1f1-8b7255ebf0e2' ) / Items (2) \",\ "ETag \": \ "\\" \\ 4 "\", \ "Тип \": \ "SP.Data.6001C5110ListItem \"}, \ "Автор \": {\ "__ метаданных \": {\"идентификатор \": \ "e10cdb3d-b3da-4f1f-8a64-fca71ddeafa9 \", \ "типа \": \ "SP.Data.UserInfoItem \"}, \ "Id \": 5, \ "Название \":\ "Имя пользователя здесь> \"}, \ "Id \": 2, \ "ID \": 2, \ "Title \": \ "6001-C5-110 Test 2 A \", \ "Start1 \": \ "2018-11-19T17: 00: 00.000Z \", \ "OData__x0045_nd1 \": \ "2018-11-19T19: 00: 00.000Z \", \ "RecurrenceRule \": нулевой, \ "RecurrenceParentID \": null, \ "CategoryDescription \": \ "Test2 \", \ "IsAllDay \": false} "

Создание выглядит следующим образом:" {\ "startTimezone \": \ "\", \"endTimezone \": \ "\", \ "recurrenceException \": \ "\", \ "ID \": null, \ "Title \": \ "Без заголовка \", \ "Start1 \": \ "2018-11-06T05: 00: 00.000Z \», \ "OData__x0045_nd1 \": \ "2018-11-06T05: 00: 00.000Z \", \ "RecurrenceRule \": \ "\", \ "RecurrenceParentID \":0, \ "CategoryDescription \": \ "\", \ "IsAllDay \": true} "

Я думаю, что тег __metadata необходим.При попытке создания я получаю сообщение от сервера:

"{\" error \ ": {\" code \ ": \" - 1, Microsoft.SharePoint.Client.InvalidClientQueryException \ ",\ "message \": {\ "lang \": \ "en-US \", \ "value \": \ "Обнаружена запись без имени типа, но не указан ожидаемый тип.Чтобы разрешить записи без информации о типе, ожидаемый тип также должен быть указан при указании модели. \ "}}}"

Как я уже упоминал, я получаю сообщение об ошибке неверного запроса в jquery.

Вот мой код планировщика:

$("#scheduler").kendoScheduler({
    date: new Date("2018/11/11"),
    startTime: new Date("2018/11/11 07:00 AM"),
    height: 600,
    views: [
        "day",
        "workWeek",
        "week",
        { type: "month", selected: true },
        "agenda",
        { type: "timeline", eventHeight: 50}
    ],
    save: function (e)
    {
        // alert('scheduler save');
    },
    dataSource: {
        transport: {
            read: {
                url: "https://<ShrePoint Site Collection>/_api/web/lists/getbytitle('6001-C5-110')/items?$expand=Author&$select=Author/Id,Author/Title,ID,Title,Start1,OData__x0045_nd1,RecurrenceRule,RecurrenceParentID,CategoryDescription,IsAllDay&$filter=Start1 ge datetime'2018-11-01T00:00:00Z'",
                //url: "https://demos.telerik.com/kendo-ui/service/tasks",
                beforeSend: function (xhr) {
                    xhr.setRequestHeader("Accept", "application/json; odata=verbose");
                },
            },
            update:
                {
                    url: function (data) {
                        return "https://<SharePoint site collection>/_api/web/lists/getbytitle('6001-C5-110')/items" + "(" + data.ID + ")";
                    },
                    type: "POST",
                    dataType: "json",
                    contentType: "application/json;odata=verbose",
                    headers: {
                        "accept": "application/json;odata=verbose",
                        "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                        "If-Match": "*",
                        "X-HTTP-Method": "MERGE",
                    },
                },
            create: {
                // The create function should perform a similar routine as the update one with a couple of notable differences:
                //      •The newly created data items have no ID, so they must be added by the function script or returned by the remote service.
                //      •The newly created data items must be returned in the success method with their IDs assigned. Otherwise, the DataSource 
                //          instance is going to operate with incorrect data and subsequent data operations can fail.
                //      •If the schema.data configuration is set, the success method should receive the created data item in an object 
                //          with the same structure as the object that is passed to the success method of the read function. See the example below.

                url: function (data) {
                    return "https://<SharePoint Site collection>/_api/web/lists/getbytitle('6001-C5-110')/items";
                },
                type: "POST",
                dataType: "json",
                contentType: "application/json;odata=verbose",
                headers: {
                    "accept": "application/json;odata=verbose",
                    "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                },
                success: function (data) {
                    alert('Success!');
                },
                error:  function (error) {
                    alert('Error!');
                    console.log(JSON.stringify(error));
                },
            },
            save: function (e) 
            {
                alert('saving');
            },
            parameterMap: function (data, type) {

                return kendo.stringify(data);
            }
        },
        schema: {
            data: function (data) {
                return data.d && data.d.results ? data.d.results : [data.d];
            },
            model: {
                id: "id",
                fields: {
                    id: { from: "ID", type: "number" },
                    title: { from: "Title", defaultValue: "No title", validation: { required: true } },
                    start: { type: "date", from: "Start1" },
                    end: { type: "date", from: "OData__x0045_nd1" },
                    recurrenceRule: { from: "RecurrenceRule" },
                    recurrenceId: { from: "RecurrenceParentID", type: "number" },
                    description: { from: "CategoryDescription" },
                    isAllDay: { type: "boolean", from: "IsAllDay" }
                }
            }
        }
    }
});

Спасибо за ваше время!

1 Ответ

0 голосов
/ 28 ноября 2018

Добавлено свойство __metadata в разделе parameterMap, теперь работает (очевидно, не будут имена жестких списков кодов, это просто для того, чтобы оно заработало):

if (type == "create") {
    return kendo.stringify({
        Title: data.Title,
        Start1: data.Start1,
        OData__x0045_nd1: data.OData__x0045_nd1,
        Id: type != "create" ? data.Id : undefined,
        CategoryDescription: data.CategoryDescription,
        __metadata: type == "create" ? { type: "SP.Data.6001C5110ListItem" } : undefined
   });
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...