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

时间:2015-11-27 13:07:12

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

我正在开发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;
        }
    }

select body中的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控制器中的Delete方法:

    [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();
    }

1 个答案:

答案 0 :(得分:0)

代码中的主要错误来自使用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