【问题标题】:Update and Delete does not work in jqGrid更新和删除在 jqGrid 中不起作用
【发布时间】:2015-11-27 13:07:12
【问题描述】:

我正在开发 web api 项目,我想用 CRUD 操作实现网格。 这些是我的 web 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

更新: 这是我目前在网格中的数据行(我只是发布图片): 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;
        }
    }

选择正文中的 Linq 语句与我的实体模型类属性相对应。

这是我的网格的定义:

更新:

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"
    });

更新: 这是我从 web 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();
    }

【问题讨论】:

  • 你在updateDialog(action)的代码中使用了params.url += rowData.Id;params.mtype = action;。在返回的对象内部使用mtype: action 并使用params.url = API_URL + rowData.Id;(或API_URL + "/")会不会更容易?无论如何,我建议您使用Fiddler 或 IE/Chrome 的开发者工具来捕获客户端和服务器之间的 HTTP 流量。您应该验证 jqGrid 发布的数据是否正确。此外,您应该始终编写您使用哪个版本的 jqGrid 以及哪个 fork(免费 jqGrid、Guriddo jqGrid JS、...)
  • 我用的是:trirand.jqGrid.4.6.0版本(免费)jqGrid。我在返回的对象和 params.url = API_URL + rowData.Id 中编写 mtype: action ,但没有幸运,仍然无法正常工作。
  • 您是否对 HTTP 流量进行了跟踪?它不仅对故障排除有好处,而且对理解你的程序真正做了什么也很有好处。您还可以看到其他错误消息。

标签: javascript jquery jqgrid asp.net-web-api2


【解决方案1】:

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

添加/编辑的正确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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-01
    • 2020-07-07
    • 2015-02-02
    • 1970-01-01
    相关资源
    最近更新 更多