2

这是我第一次尝试在 ASP.NET MVC 4 中使用 jqGrid,所以请原谅 newby 的问题。我似乎已经完成了所有工作,但是当在内联添加期间保存一行时,网格显示 jqg1 而不是从数据库返回的 id。id 在那里,但由于某种原因它没有被显示。当我刷新网格时,id 会正确显示,所以它肯定也在数据库中。任何想法将不胜感激。谢谢!!

网格

    <script type="text/javascript">
    $(document).ready(function () {
        var grid = $('#list'),
            decodeErrorMessage = function (jqXHR, textStatus, errorThrown) {
                var html, errorInfo, i, errorText = textStatus + '\n' + errorThrown;
                if (jqXHR.responseText.charAt(0) === '[') {
                    try {
                        errorInfo = $.parseJSON(jqXHR.responseText);
                        errorText = "";
                        for (i = 0; i < errorInfo.length; i++) {
                            if (errorText.length !== 0) {
                                errorText += "<hr/>";
                            }
                            errorText += errorInfo[i].Source + ": " + errorInfo[i].Message;
                        }
                    }
                    catch (e) { }
                } else {
                    html = /<body.*?>([\s\S]*)<\/body>/i.exec(jqXHR.responseText);
                    if (html !== null && html.length > 1) {
                        errorText = html[1];
                    }
                }
                return errorText;
            };
        grid.jqGrid({
            url: '@Url.Action("DynamicGridData", "Team")',
            datatype: "json",
            mtype: 'POST',
            colNames: ['Id', 'Code', 'Name'],
            colModel: [
                {
                    name: 'TeamId', index: 'TeamId', key: true, width: 50,
                    searchoptions: {
                        sopt: ['eq', 'ne', 'lt', 'le', 'gt', 'ge'],
                        dataInit: function (elem) {
                            $(elem).autocomplete({ source: '@Url.Action("GetIdsAutoComplete", "Team")' });
                        }
                    }
                },
                {
                    name: 'Code', index: 'Code', width: 75, editable: true,
                    searchoptions: {
                        sopt: ['cn', 'nc', 'bw', 'bn', 'eq', 'ne', 'ew', 'en', 'lt', 'le', 'gt', 'ge'],
                        dataInit: function (elem) {
                            $(elem).autocomplete({ source: '@Url.Action("GetCodesAutoComplete", "Team")' });
                        }
                    }
                },
                {
                    name: 'Name', index: 'Name', width: 200, editable: true,
                    searchoptions: {
                        sopt: ['cn', 'nc', 'bw', 'bn', 'eq', 'ne', 'ew', 'en', 'lt', 'le', 'gt', 'ge'],
                        dataInit: function (elem) {
                            $(elem).autocomplete({ source: '@Url.Action("GetNamesAutoComplete", "Team")' });
                        }
                    }
                }
            ],
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: '#pager',
            rownumbers: true,
            sortname: 'TeamId',
            sortorder: "desc",
            viewrecords: true,
            altRows: true,
            altclass: 'myAltRowClass',
            width: 700,
            height: 200,
            gridview: true,
            jsonReader: { cell: "" },
            editurl: '@Url.Action("Update", "Team")',
            caption: "Teams",
            loadError: function (jqXHR, textStatus, errorThrown) {
                // remove error div if exist
                $('#' + this.id + '_err').remove();
                // insert div with the error description before the grid
                grid.closest('div.ui-jqgrid').before(
                    '<div id="' + this.id + '_err" style="max-width:' + this.style.width +
                    ';"><div class="ui-state-error ui-corner-all" style="padding:0.7em;float:left;"><span class="ui-icon ui-icon-alert" style="float:left; margin-right: .3em;"></span><span style="clear:left">' +
                    decodeErrorMessage(jqXHR, textStatus, errorThrown) + '</span></div><div style="clear:left"/></div>');
            },
            loadComplete: function () {
                // remove error div if exist
                $('#' + this.id + '_err').remove();
            }
        });
        grid.jqGrid('filterToolbar', { stringResult: true, searchOnEnter: true, defaultSearch: 'cn' });
        grid.jqGrid('navGrid', '#pager', { add: false, edit: false },
              {}, {}, {}, { multipleSearch: true, overlay: false, width: 480, showQuery: true });
        grid.jqGrid('inlineNav', "#pager");
        grid.jqGrid('navButtonAdd', '#pager',
                    {
                        caption: "", title: "Toggle Searching Toolbar",
                        buttonicon: 'ui-icon-gear',
                        onClickButton: function () { grid[0].toggleToolbar(); }
                    });
    });
</script>

控制器

        // POST: /Team/Update/5

    [HttpPost]
    public ActionResult Update(Team Team, string oper)
    {
        try
        {
            switch (oper)
            {
                case "add":
                    unitOfWork.TeamRepository.Insert(Team);
                    unitOfWork.Save();
                    return RedirectToAction("Search");
                case "edit":
                    if (ModelState.IsValid)
                    {
                        unitOfWork.TeamRepository.Update(Team);
                        unitOfWork.Save();
                        return RedirectToAction("Search");
                    }
                    break;
            }
        }
        catch (DbUpdateConcurrencyException ex)
        {
            var entry = ex.Entries.Single();
            var databaseValues = (Team)entry.GetDatabaseValues().ToObject();
            var clientValues = (Team)entry.Entity;
            if (databaseValues.Code != clientValues.Code)
                ModelState.AddModelError("Code", "Current value: "
                    + databaseValues.Code);
            if (databaseValues.Name != clientValues.Name)
                ModelState.AddModelError("Name", "Current value: "
                    + databaseValues.Name);
            ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                + "was modified by another user after you got the original value. The "
                + "edit operation was canceled and the current values in the database "
                + "have been displayed. If you still want to edit this record, click "
                + "the Save button again. Otherwise click the Back to List hyperlink.");
        }
        catch (DataException)
        {
            //Log the error (add a variable name after DataException)
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }
        return View(Team);
    }

将控制器 ActionResult 修改为下面,但仍会在网格中显示 jqg1,直到我通过 inlineNav 按钮重新加载它。数据库正在更新,但网格最初显示 jqg1,直到重新加载。有任何想法吗?谢谢!!

[HttpPost]
    public ActionResult Update(Team Team, string oper)
    {
        try
        {
            if (oper.Equals("add"))
            {
                unitOfWork.TeamRepository.Insert(Team);
                unitOfWork.Save();
            }
            else if (oper.Equals("edit"))
            {
                if (ModelState.IsValid)
                {
                    unitOfWork.TeamRepository.Update(Team);
                    unitOfWork.Save();
                }
            }
        }
        catch (DbUpdateConcurrencyException ex)
        {
            var entry = ex.Entries.Single();
            var databaseValues = (Team)entry.GetDatabaseValues().ToObject();
            var clientValues = (Team)entry.Entity;
            if (databaseValues.Code != clientValues.Code)
                ModelState.AddModelError("Code", "Current value: "
                    + databaseValues.Code);
            if (databaseValues.Name != clientValues.Name)
                ModelState.AddModelError("Name", "Current value: "
                    + databaseValues.Name);
            ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                + "was modified by another user after you got the original value. The "
                + "edit operation was canceled and the current values in the database "
                + "have been displayed. If you still want to edit this record, click "
                + "the Save button again. Otherwise click the Back to List hyperlink.");
        }
        catch (DataException)
        {
            //Log the error (add a variable name after DataException)
            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
        }

        var context = new NonTaxContext();
        return Json(new
        {
            total = 1,
            page = 1,
            records = 1,
            rows = (from item in context.Teams
                    where item.TeamId.Equals(Team.TeamId)
                    select item.TeamId).ToList()
        });
    }
4

1 回答 1

1

问题是inlineNav在向数据库添加数据的情况下,您使用的工作不够好。所以你必须在添加行之后做一些额外的步骤aftersavefunc

grid.jqGrid("inlineNav", "#pager", {
    addParams: {
        addRowParams: {
            aftersavefunc: function (rowId, jqXHR) {
                // here you need place some additional code !!!
                // jqXHR is a superset of the XMLHTTPRequest object
                // typically one need use jqXHR.responseText
                // to access the response from the server
            }
        }
    },
    ... // other options which you need
});

该问题的最简单解决方案是在添加新行后重新加载网格内容:

aftersavefunc: function () {
    var $this = $(this); // grid
    setTimeout(function () {
        $this.trigger("reloadGrid");
    }, 50);
}

或者,您可以从数据库返回新行的 id。您当前的代码返回RedirectToAction("Search");,这似乎是我的错误。如果您返回新行的 id,您可以在其中获取jqXHR.responseTextaftersavefunc

aftersavefunc: function function (rowId, jqXHR) {
    var newRowId = jqXHR.responseText; // probably $.parseJSON(jqXHR.responseText)
    $(this).jqGrid("setCell", rowId, "TeamId", newRowId);
    $("#" + $.jgrid.jqID(rowId)).attr("id", newRowId);
}
于 2013-03-11T21:14:09.053 回答