JQWidget Grid - 即使在语句之前也会更改rowdata

时间:2018-01-11 10:03:54

标签: javascript jquery jqxgrid jqwidget

我在使用JQWidget-jqxGrid时遇到了一些麻烦。我想更改从行版本发送到API的格式信息。我需要将一些日期更改为特定的字符串表示法。这是我现在正在使用的代码:

updaterow: function (rowid, rowdata, commit)
            {
                //console.log(rowdata);
                var output = rowdata;

                for (property in output) {
                    if (output[property] instanceof Date && schema.properties[property].format === "time") {
                        output[property] = output[property].getHours() + ":" + output[property].getMinutes();
                        //console.log('hola');
                    }
                    if (output[property] instanceof Date && schema.properties[property].format === "date")
                    {
                        output[property] = output[property].getFullYear() + "-" + output[property].getMonth() + 1 + '-' + output[property].getDate();
                    }
                }

                /*console.log(event.args.row);*/
                console.log(output);
                console.log(rowdata);

                var token = $('input[name="__RequestVerificationToken"]').val();

                $.ajax({
                    url: "/api/" + entity + "/" + rowdata.uid,
                    cache: false,
                    method: "put",
                    data: JSON.stringify(rowdata),
                    processData: false,
                    headers: {
                        "RequestVerificationToken": token,
                        "Content-type": "Application/json"
                    },
                    success: function () {
                        console.log("Okey dokey!");
                        commit(true);
                    },
                    error: function () {
                        alert("El dato no se ha actualizado correctamente");
                    }
                });
            }

在做这件事之前我尝试了很多东西。最初,我正在对“oncelledit”事件进行更新,问题是一样的(这对我来说就像某种超自然现象):

正如您所看到的,我正在重新格式化输出变量中的数据,而不是rowdata。即便如此,在为ajax请求修改输出变量之前,如果我取消注释“console.log(rowdata);”,则数据将在修改数据的“for”范围之前已经更改。这怎么可能?我使用其他浏览器检查了缓存,但没有运气。

虽然使用此代码将数据正确发布到我的API,但数据格式在显示给用户的网格上更改,数据变得ouwfull。我想以适当的格式发送信息,但不要更改网格中显示的格式数据。

这是在版本之前显示数据的方式:
fecha de inicio | hora de inicio
1/10/2018 |上午8:00

这是在版本之后:
fecha de inicio | hora de inicio
2001-01-1 | 13:0

我发布完整代码以防万一:

-JSGrid.js -

$.ajaxSetup({ cache: false });
var FKSources = [];
var FKAdapters = {};
var dataFieldsArr = [];
var columnsArr = [];
var FKPropertySelection;
var entity;
var schema;

function createGrid()
{
    $.ajax({
        url: "/api/" + entity + "/schema",
        success: function (data) {
            schema = data;
            for (property in data.properties) {
                if (data.properties[property]["type"].indexOf("lhcrud") > -1) {
                    FKSources.push({
                        datatype: "json",
                        datafields:
                        [
                            { name: data.fkAttributes[property] },
                            { name: 'id', type: 'int' }
                        ],
                        id: 'id',
                        url: '/api/' + data.properties[property]["type"].substring(data.properties[property]["type"].indexOf("models.") + "models.".length)
                    });
                    FKAdapters[property] = new $.jqx.dataAdapter(FKSources[FKSources.length - 1]);
                    dataFieldsArr.push({
                        name: property + 'Id',
                        value: property + 'Id',
                        values:
                        {
                            source: FKAdapters[property].records,
                            value: 'id',
                            label: data.fkAttributes[property]
                        },
                        type: 'int'
                    });
                    dataFieldsArr.push({
                        name: property + 'Nombre',
                        type: 'string',
                        map: property + '>' + data.fkAttributes[property]
                    });
                    columnsArr.push(
                        {
                            text: data.properties[property]["title"],
                            columntype: 'dropdownlist',
                            datafield: property + 'Id',
                            width: 150,
                            filtertype: 'checkedlist',
                            displayfield: property + 'Nombre',
                            createeditor: function (row, value, editor) {
                                editor.jqxDropDownList({ source: FKAdapters[FKPropertySelection], displayMember: data.fkAttributes[FKPropertySelection], valueMember: 'id' });
                            }
                        }
                    );
                }
                else if (data.properties[property]["type"].indexOf("integer") > -1) {
                    dataFieldsArr.push({ name: property, type: 'int' });
                    columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 80, cellsalign: 'right' });
                }
                else if (data.properties[property]["type"].indexOf("boolean") > -1) {
                    dataFieldsArr.push({ name: property, type: 'bool' });
                    columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 65, columntype: 'checkbox' });
                }
                else if (data.properties[property]["format"].indexOf("date") > -1) {
                    dataFieldsArr.push({ name: property, type: 'date' });
                    columnsArr.push({
                        text: data.properties[property]["title"], datafield: property, width: 150, columntype: 'datetimeinput', cellsalign: 'right', cellsformat: 'd'
                    });
                }
                else if (data.properties[property]["format"].indexOf("time") > -1) {
                    dataFieldsArr.push({ name: property, type: 'date' });
                    columnsArr.push({
                        text: data.properties[property]["title"], datafield: property, width: 100, columntype: 'datetimeinput', cellsalign: 'right', cellsformat: 't', createeditor: function (row, column, editor) {
                            editor.jqxDateTimeInput({
                                showTimeButton: true,
                                showCalendarButton: false
                            });
                        }
                    });
                }
                else {
                    dataFieldsArr.push({ name: property, type: 'string' });
                    columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 150 });
                }
            }

            columnsArr.push({
                text: 'Delete', datafield: 'Delete', columntype: 'button', width: 90, cellsrenderer: function () {
                    return "Delete row";
                }, buttonclick: function (row) {
                    var deleteConfirm = confirm("Sure?");
                    if (deleteConfirm) {
                        var id = $("#jqxgrid").jqxGrid('getrowid', row);
                        deleteEntity(entity, id, $('input[name="__RequestVerificationToken"]').val());
                        $('#jqxgrid').jqxGrid('deleterow', id);
                    }
                }
            });

            var source =
            {
                datatype: "json",
                datafields: dataFieldsArr,
                id: 'id',
                url: '/api/' + entity,
                addrow: function (rowid, rowdata, position, commit) {
                    var token = $('input[name="__RequestVerificationToken"]').val();

                    //console.log(rowid);
                    //console.log(rowdata);
                    $.ajax({
                        url: "/api/" + entity,
                        method: "post",
                        data: JSON.stringify(rowdata),
                        processData: false,
                        headers: {
                            "RequestVerificationToken": token,
                            "Content-type": "Application/json"
                        },
                        success: function () {
                            commit(true);

                            //reload Data in order to manage correctly new data
                            $("#jqxgrid").jqxGrid(
                                {
                                    source: dataAdapter,
                                    sortable: true,
                                    filterable: true,
                                    editable: true,
                                    showeverpresentrow: true,
                                    everpresentrowposition: "top",
                                    selectionmode: 'singlecell',
                                    editmode: 'dblclick',
                                    theme: 'light',
                                    columns: columnsArr
                                });
                        },
                        error: function (xhr) {
                            console.log(xhr);
                            commit(false);
                        }
                    });
                },
                updaterow: function (rowid, rowdata, commit)
                {
                    //console.log(rowdata);
                    var output = rowdata;

                    for (property in output) {
                        if (output[property] instanceof Date && schema.properties[property].format === "time") {
                            output[property] = output[property].getHours() + ":" + output[property].getMinutes();
                            //console.log('hola');
                        }
                        if (output[property] instanceof Date && schema.properties[property].format === "date")
                        {
                            output[property] = output[property].getFullYear() + "-" + output[property].getMonth() + 1 + '-' + output[property].getDate();
                        }
                    }

                    /*console.log(event.args.row);*/
                    console.log(output);
                    console.log(rowdata);

                    var token = $('input[name="__RequestVerificationToken"]').val();

                    $.ajax({
                        url: "/api/" + entity + "/" + rowdata.uid,
                        cache: false,
                        method: "put",
                        data: JSON.stringify(rowdata),
                        processData: false,
                        headers: {
                            "RequestVerificationToken": token,
                            "Content-type": "Application/json"
                        },
                        success: function () {
                            console.log("Okey dokey!");
                            commit(true);
                        },
                        error: function () {
                            alert("El dato no se ha actualizado correctamente");
                        }
                    });
                }
            };

            var dataAdapter = new $.jqx.dataAdapter(source);

            $("#jqxgrid").jqxGrid(
                {
                    source: dataAdapter,
                    width: '100%',
                    sortable: true,
                    filterable: true,
                    editable: true,
                    showeverpresentrow: true,
                    everpresentrowposition: "top",
                    selectionmode: 'singlecell',
                    editmode: 'dblclick',
                    theme: 'light',
                    columns: columnsArr
                });
        },
        error: function () {
            alert("Error Getting Data");
        }
    });
}

$("#jqxgrid").on('cellselect', function (event) {
    FKPropertySelection = event.args.datafield.substring(0, event.args.datafield.indexOf('Id'));
});

$.ajaxSetup({ cache: false }); var FKSources = []; var FKAdapters = {}; var dataFieldsArr = []; var columnsArr = []; var FKPropertySelection; var entity; var schema; function createGrid() { $.ajax({ url: "/api/" + entity + "/schema", success: function (data) { schema = data; for (property in data.properties) { if (data.properties[property]["type"].indexOf("lhcrud") > -1) { FKSources.push({ datatype: "json", datafields: [ { name: data.fkAttributes[property] }, { name: 'id', type: 'int' } ], id: 'id', url: '/api/' + data.properties[property]["type"].substring(data.properties[property]["type"].indexOf("models.") + "models.".length) }); FKAdapters[property] = new $.jqx.dataAdapter(FKSources[FKSources.length - 1]); dataFieldsArr.push({ name: property + 'Id', value: property + 'Id', values: { source: FKAdapters[property].records, value: 'id', label: data.fkAttributes[property] }, type: 'int' }); dataFieldsArr.push({ name: property + 'Nombre', type: 'string', map: property + '>' + data.fkAttributes[property] }); columnsArr.push( { text: data.properties[property]["title"], columntype: 'dropdownlist', datafield: property + 'Id', width: 150, filtertype: 'checkedlist', displayfield: property + 'Nombre', createeditor: function (row, value, editor) { editor.jqxDropDownList({ source: FKAdapters[FKPropertySelection], displayMember: data.fkAttributes[FKPropertySelection], valueMember: 'id' }); } } ); } else if (data.properties[property]["type"].indexOf("integer") > -1) { dataFieldsArr.push({ name: property, type: 'int' }); columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 80, cellsalign: 'right' }); } else if (data.properties[property]["type"].indexOf("boolean") > -1) { dataFieldsArr.push({ name: property, type: 'bool' }); columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 65, columntype: 'checkbox' }); } else if (data.properties[property]["format"].indexOf("date") > -1) { dataFieldsArr.push({ name: property, type: 'date' }); columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 150, columntype: 'datetimeinput', cellsalign: 'right', cellsformat: 'd' }); } else if (data.properties[property]["format"].indexOf("time") > -1) { dataFieldsArr.push({ name: property, type: 'date' }); columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 100, columntype: 'datetimeinput', cellsalign: 'right', cellsformat: 't', createeditor: function (row, column, editor) { editor.jqxDateTimeInput({ showTimeButton: true, showCalendarButton: false }); } }); } else { dataFieldsArr.push({ name: property, type: 'string' }); columnsArr.push({ text: data.properties[property]["title"], datafield: property, width: 150 }); } } columnsArr.push({ text: 'Delete', datafield: 'Delete', columntype: 'button', width: 90, cellsrenderer: function () { return "Delete row"; }, buttonclick: function (row) { var deleteConfirm = confirm("Sure?"); if (deleteConfirm) { var id = $("#jqxgrid").jqxGrid('getrowid', row); deleteEntity(entity, id, $('input[name="__RequestVerificationToken"]').val()); $('#jqxgrid').jqxGrid('deleterow', id); } } }); var source = { datatype: "json", datafields: dataFieldsArr, id: 'id', url: '/api/' + entity, addrow: function (rowid, rowdata, position, commit) { var token = $('input[name="__RequestVerificationToken"]').val(); //console.log(rowid); //console.log(rowdata); $.ajax({ url: "/api/" + entity, method: "post", data: JSON.stringify(rowdata), processData: false, headers: { "RequestVerificationToken": token, "Content-type": "Application/json" }, success: function () { commit(true); //reload Data in order to manage correctly new data $("#jqxgrid").jqxGrid( { source: dataAdapter, sortable: true, filterable: true, editable: true, showeverpresentrow: true, everpresentrowposition: "top", selectionmode: 'singlecell', editmode: 'dblclick', theme: 'light', columns: columnsArr }); }, error: function (xhr) { console.log(xhr); commit(false); } }); }, updaterow: function (rowid, rowdata, commit) { //console.log(rowdata); var output = rowdata; for (property in output) { if (output[property] instanceof Date && schema.properties[property].format === "time") { output[property] = output[property].getHours() + ":" + output[property].getMinutes(); //console.log('hola'); } if (output[property] instanceof Date && schema.properties[property].format === "date") { output[property] = output[property].getFullYear() + "-" + output[property].getMonth() + 1 + '-' + output[property].getDate(); } } /*console.log(event.args.row);*/ console.log(output); console.log(rowdata); var token = $('input[name="__RequestVerificationToken"]').val(); $.ajax({ url: "/api/" + entity + "/" + rowdata.uid, cache: false, method: "put", data: JSON.stringify(rowdata), processData: false, headers: { "RequestVerificationToken": token, "Content-type": "Application/json" }, success: function () { console.log("Okey dokey!"); commit(true); }, error: function () { alert("El dato no se ha actualizado correctamente"); } }); } }; var dataAdapter = new $.jqx.dataAdapter(source); $("#jqxgrid").jqxGrid( { source: dataAdapter, width: '100%', sortable: true, filterable: true, editable: true, showeverpresentrow: true, everpresentrowposition: "top", selectionmode: 'singlecell', editmode: 'dblclick', theme: 'light', columns: columnsArr }); }, error: function () { alert("Error Getting Data"); } }); } $("#jqxgrid").on('cellselect', function (event) { FKPropertySelection = event.args.datafield.substring(0, event.args.datafield.indexOf('Id')); });

-JSGrid.cshtml -

@{
    ViewData["Title"] = "JSGrid";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<h2>JSGrid for @ViewBag.entity</h2>
@Html.AntiForgeryToken()
<div id="jqxgrid">
</div>

@section scripts
{
    <link rel="stylesheet" href="~/lib/jqwidgets/styles/jqx.base.css" type="text/css" />
    <link rel="stylesheet" href="~/lib/jqwidgets/styles/jqx.light.css" type="text/css" />
    <script type="text/javascript" src="~/lib/jqwidgets/jqxcore.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxdata.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxbuttons.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxscrollbar.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxmenu.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxlistbox.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxdropdownlist.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxcheckbox.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxdatetimeinput.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxcalendar.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxtooltip.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.selection.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.columnsresize.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.filter.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.sort.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.pager.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.grouping.js"></script>
    <script type="text/javascript" src="~/lib/jqwidgets/jqxgrid.edit.js"></script>
    <script type="text/javascript" src="~/js/JSGrid.js"></script>

    <script>
        entity = '@ViewBag.entity';
        createGrid();
    </script>
}

提前致谢!

1 个答案:

答案 0 :(得分:0)

好的,好的!我在这里找到了解决方案:

https://www.jqwidgets.com/community/topic/rowdata-changed-even-before-statement-to-do-so/#post-98256

在这里:

https://www.jqwidgets.com/community/topic/difference-between-refreshdata-and-updatebounddata/ (¡Haya PAZ! - Les luthiers)

我用jqxgrid中的'updatebounddata'方法部分解决了重新加载绑定数据的问题。

万一有人遇到同样的问题,我将离开这里更新我的updateRow函数。看看ajax块:

updaterow: function (rowid, rowdata, commit)
                {
                    //console.log(rowdata);
                    var output = rowdata;

                    for (property in output) {
                        if (output[property] instanceof Date && schema.properties[property].format === "time") {
                            output[property] = output[property].getHours() + ":" + output[property].getMinutes();
                            //console.log('hola');
                        }
                        if (output[property] instanceof Date && schema.properties[property].format === "date")
                        {
                            output[property] = output[property].getFullYear() + "-" + (output[property].getMonth() + 1) + '-' + output[property].getDate();
                        }
                    }

                    //console.log(event.args.row);
                    //console.log(output);
                    //console.log(rowdata);

                    var token = $('input[name="__RequestVerificationToken"]').val();

                    $.ajax({
                        url: "/api/" + entity + "/" + rowdata.uid,
                        cache: false,
                        method: "put",
                        data: JSON.stringify(rowdata),
                        processData: false,
                        headers: {
                            "RequestVerificationToken": token,
                            "Content-type": "Application/json"
                        },
                        success: function () {
                            console.log("Okey dokey!");
                            commit(true);
                            $("#jqxgrid").jqxGrid('updatebounddata');
                        },
                        error: function () {
                            alert("El dato no se ha actualizado correctamente");
                            $("#jqxgrid").jqxGrid('updatebounddata');
                        }
                    });
                }

希望这将有助于将来的某个人!