数据表编辑器不会反映修改后的数据

时间:2019-05-04 17:17:57

标签: json ajax datatables jquery-datatables-editor

我最近为我的ASPNET Core网站实现了Datatables.Editor功能,在用户提交数据后,我无法获取数据以反映前端的更改。数据已在后端正确更新,并且Web控制台中没有错误。

客户端

<script>
    var editor;
    $(document).ready(function () {
        editor = new $.fn.dataTable.Editor({
            //ajax: "/api/sales/@Model.Id",
            ajax: {
                url: '/api/sales/@Model.Id',
                dataSrc: '',
                data: function (d) {
                    return JSON.stringify(d);
                },
                contentType: "application/json"
            },
            formOptions: {
                inline: {
                    onBlur: true
                }
            },
            idSrc:  'Id',
            table: "#example",
            fields: [{
                label: "ID:",
                name: "Id",
                def: 0
            }, {
                label: "Name:",
                name: "Name"
            }, {
                label: "Price:",
                name: "SalePrice"
            }, {
                label: "Start Date:",
                name: "StartDate",
                type: "datetime"
            }, {
                label: "Finish Date:",
                name: "FinishDate",
                type: "datetime"
            }]
        });

        var editIcon = function (data, type, row) {
            if (type === 'display') {
                return data + ' <i class="fas fa-pencil-alt"/>';
            }
            return data;
        };

        $('#example tbody').on('click', 'td i', function (e) {
            e.stopImmediatePropagation(); // stop the row selection when clicking on an icon

            editor.inline($(this).parent(), {
                submit: 'allIfChanged'
            });
        });

        $('#example').DataTable({
            ajax: {
                url: '/api/sales/@Model.Id',
                dataSrc: '',
                contentType: "application/json"
            },
            idSrc:  'Id',
            dom: "Bfrtip",
            columns: [
                { data: "Id" },
                { data: "Name", render: editIcon },
                { data: "SalePrice", render: editIcon },
                { data: "StartDate", render: editIcon },
                { data: "FinishDate", render: editIcon }
            ],
            select: true,
            buttons: [
                { extend: "create", editor: editor },
                { extend: "edit", editor: editor },
                { extend: "remove", editor: editor }
            ]
        });
    });
</script>

GET响应示例:

[{"Id":1,"Name":"Test","StartDate":"2019-05-04T00:00:00","FinishDate":"2019-05-31T00:00:00","SalePrice":30.0}]

示例POST正文:

{"action":"edit","data":{"1":{"Id":"1","Name":"Test","SalePrice":"30","StartDate":"2019-05-04","FinishDate":"2019-05-31"}}}

POST响应示例:

{"Id":1,"Name":"Test","StartDate":"2019-05-04T00:00:00","FinishDate":"2019-05-31T00:00:00","SalePrice":29.0}

0 个答案:

没有答案