gpt4 book ai didi

jquery - 在内联添加时显示 jqg1 而不是从数据库返回的 id

转载 作者:行者123 更新时间:2023-12-01 04:54:42 26 4
gpt4 key购买 nike

这是我第一次尝试在 ASP.NET MVC 4 中使用 jqGrid,所以请原谅新手的问题。我似乎一切正常,但是当在内联添加期间保存一行时,网格显示 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>

Controller

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

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

最佳答案

问题是您使用的 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,则可以在 aftersavefunc

内将其作为 jqXHR.responseText 获取
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);
}

关于jquery - 在内联添加时显示 jqg1 而不是从数据库返回的 id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15345391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com