ASP.NET MVC 4 で jqGrid を使用するのはこれが初めての試みなので、newby の質問をお許しください。私は自分の側ですべてが機能しているように見えますが、インライン追加中に行が保存されると、データベースから返される ID の代わりにグリッドに jqg1 が表示されます。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);
}
Controller ActionResult を以下に変更しましたが、inlineNav ボタンを介してリロードするまでグリッドに jqg1 を表示したままです。データベースは更新されていますが、グリッドは再ロードされるまで最初は 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()
});
}