更新和删除在 jqGrid 中不起作用

Update and Delete does not work in jqGrid

我正在从事 Web api 项目,我想使用 CRUD 操作实现网格。 这些是我的网络 api 方法:

[HttpGet]
public HttpResponseMessage GetAllPosting() {}

[HttpGet]
public HttpResponseMessage GetPostingById(int Id) {}

[HttpPost]
public HttpResponseMessage Post([FromBody] vGeneralLedger item) {}

[HttpPut]
public HttpResponseMessage Put(int id, vGeneralLedger item) {}

[HttpDelete]
public void Delete(int id) {}

在我的视图页面中,我定义了jQgrid:

jQuery("#generalLedgerGrid").jqGrid({
...
...
});

function updateDialog(action) {
    return {
        url: API_URL, // 'http://localhost:xxxxx/api/GeneralLedgerDetails/'
        closeAfterAdd: true,
        closeAfterEdit: true,
        afterShowForm: function (formId) { },
        jqmodal: true,
        afterSubmit: function (params) {
            var list = $("#generalLedgerGrid");
            var selectedRow = list.getGridParam("selrow");
            rowData = list.getRowData(selectedRow);
            params.url += rowData.Id;
            params.mtype = action;
        },
        bSubmit: "Submit",
        bCancel: "Cancel",
        width: "400",
        reloadAfterSubmit: true
    };
}

jQuery("#generalLedgerGrid").jqGrid('navGrid', '#generalLedgersPager',
    { edit: true, add: true, del: true },
    updateDialog('PUT'),
    updateDialog('POST'),
    updateDialog('DELETE')
);

当我 运行 应用程序时,网格显示页面(视图)中的所有数据。但是,如果我想编辑行网格或删除,则总是被重定向(当我将断点放在我的 API 方法中时)到

[HttpPost]
public HttpResponseMessage Post([FromBody] vGeneralLedger item)

以及编辑和删除功能无法正常工作。还有一个问题:当我想在网格中添加新记录(在打开的对话框中)并按保存按钮时,我的对话框仍然打开,当我关闭对话框时,我必须重新加载要显示的最新记录的页面。

而且,我已经使用了这个教程: http://techbrij.com/add-edit-delete-jqgrid-asp-net-web-api

更新: 这是我当前在网格中的数据行(我只是 post 图片): enter image description here

更新: 这是 GetAllPosting 方法

    [HttpGet]
    public HttpResponseMessage GetAllPosting()
    {
        try
        {
            var generalLedgers = _db.genLedgers.Where(x => x.Status == true).Select(a => new
            {
                Id = a.Id,
                finNaturalBusinessYearId = a.finNaturalBusinessYearId,
                finDocumentTypeId = a.finDocumentTypeId,
                AccountNo = a.AccountNo,
                PostingDate = a.PostingDate,
                MaturityDate = a.MaturityDate,
                AmountDebit = a.AmountDebit,
                AmountCredit = a.AmountCredit,
                Balance = a.Balance,
                Description = a.Description,
                DateCreated = DateTime.Now,
                UserId = 1
            });

            var formatter = new JsonMediaTypeFormatter();
            var json = formatter.SerializerSettings;
            json.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            json.Formatting = Newtonsoft.Json.Formatting.Indented;

            return Request.CreateResponse(HttpStatusCode.OK, generalLedgers, formatter);
        }
        catch (Exception ex)
        {

            throw;
        }
    }

select 主体中的 Linq 语句与我的实体模型 class 属性相对应。

这是我的网格定义:

更新:

jQuery("#generalLedgerGrid").jqGrid({
        height: 290,
        width: 1200,
        url: API_URL,
        mtype: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        serializeGridData: function (postData) {
            return JSON.stringify(postData);
        },
        jsonReader: {
            root: function (obj) { return obj; },
            page: function (obj) { return 1; },
            total: function (obj) { return 1; },
            records: function (obj) { return obj.length; },
            Id: "0",
            cell: "",
            repeatitems: false,
            celledit: false
        },
        colNames: ['Id', 'NB Year Id', 'Document Type Id', 'Account No', 'Posting Date', 'Maturity Date', 'Description', 'Total Debit', 'Total Credit', 'Balance'],
        colModel: [
            { name: 'Id', align: "center", editable: false, width: "45px" },
        { name: 'finNaturalBusinessYearId', align: "center", editable: true, width: "75px" },
        { name: 'finDocumentTypeId', align: "center", editable: true },
        { name: 'AccountNo', align: "center", editable: true },
        {
            name: 'PostingDate', align: "center", editable: true
        },
        { name: 'MaturityDate', align: "center", editable: true },
        { name: 'Description', align: "center", editable: true },
        { name: 'AmountDebit', align: "center", editable: true },
        { name: 'AmountCredit', align: "center", editable: true },
        { name: 'Balance', align: "center", editable: true }
        ],
        gridview: true,
        autoencode: true,
        ignorecase: true,
        reloadGridOptions: {fromServer: true},
        sortname: "InstallmentDate",
        sortorder: "asc",
        viewrecords: true,
        rowNum: 10,
        rowList: [10, 15, 20],
        pager: '#generalLedgersPager',
        caption: "General Ledger Posting List"
    });

更新: 这是我从网络 api 控制器中删除的方法:

    [HttpDelete]
    public void Delete(int id)
    {
        finGeneralLedger item = _db.genLedgers.Find(id);
        if (item == null)
        {
            throw new HttpResponseException(HttpStatusCode.NotFound);
        }
        item.Status = false;
        item.DateUpdated = DateTime.Now;
        item.UserId = 1;

        _db.SaveChanges();
    }

代码中的主要错误来自用法 afterSubmit。回调将在 从服务器获得响应后使用。我想你只是想使用另一个回调 onclickSubmit,但你用错了。

Add/Edit 的正确 onclickSubmit 回调可能如下

onclickSubmit: function (options, postdata, formOper) {
    options.url = API_URL + "/" + encodeURIComponent(postdata[this.id + "_id"]);
    options.mtype = formOper === "add" ? "POST" : "PUT";
}

删除对话框的选项:

{
    mtype: "DELETE",
    serializeDelData: function () {
        return ""; // the body MUST be empty in DELETE HTTP requests
    },
    onclickSubmit: function (options, postdata) {
        options.url = API_URL + "/" + encodeURIComponent(postdata);
    }
}

如果API_URL的值在字符串的末尾已经包含/,那么你应该在上面的代码片段中替换API_URL + "/" to API_URL