Asp.net mvc 如何在内联JQGrid中插入新行?
查看页面:Asp.net mvc 如何在内联JQGrid中插入新行?,asp.net-mvc,jquery-ui,jqgrid-asp.net,jqgrid-formatter,mvcjqgrid,Asp.net Mvc,Jquery Ui,Jqgrid Asp.net,Jqgrid Formatter,Mvcjqgrid,查看页面: jQuery("#theGrid").jqGrid({ url: '/Student/Grid', datatype: "json", colNames: ['Id', 'Firstname', 'Middlename', 'Lastname', 'Birthdate', 'Birthplace', 'State', 'Nationality', 'Religion', 'Ishandicaped ?', 'Actions'], colModel: [
jQuery("#theGrid").jqGrid({
url: '/Student/Grid',
datatype: "json",
colNames: ['Id', 'Firstname', 'Middlename', 'Lastname', 'Birthdate', 'Birthplace', 'State', 'Nationality', 'Religion', 'Ishandicaped ?', 'Actions'],
colModel: [
{ key: true, name: 'Id', sortable: true, resize: true, align: "center", hidden: true },
{ key: false, name: 'FirstName', index: 'FirstName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'MiddleName', index: 'MiddleName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'LastName', index: 'LastName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'Birthdate', index: 'Birthdate', editable: true, align: "center", editrules: { required: true }, formatter: 'date', editoptions: { dataInit: function (el) { setTimeout(function () { $(el).datepicker(); }, 200); } } },
{ key: false, name: 'Birthplace', index: 'Birthplace', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'State', index: 'State', editable: true, align: "center", edittype: "select", editoptions: { value: "GJ:Gujarat;MH:Maharashtra;DL:Delhi;BNG:Banglore;RJ:Rajasthan" }, editrules: { required: true } },
{ key: false, name: 'Nationality', index: 'Nationality', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'Religion', index: 'Religion', editable: true, align: "center", editrules: { required: true } },
{
key: false, name: 'IsHandicaped', index: 'IsHandicaped', editable: true, align: "center", edittype: "checkbox", editoptions: { value: "True:False" }
},
{
key: false,
name: 'Actions',
index: 'tax',
width: 80,
align: "center",
formatter: 'actions',
formatoptions: {
keys: true,
delOptions: { url: '/Student/Delete' }
}
}
],
rowNum: 10,
rownumbers: true,
autowidth: true,
rowList: [5, 10, 20],
pager: '#gridPager',
sortname: 'invdate',
viewrecords: true,
sortorder: "acc",
altRows: true,
delicon: 'glyphicon glyphicon-trash',
altclass: 'table table-striped',
jsonReader: {
repeatitems: false
},
editurl: '/Student/Edit',
mtype:"PUT",
height: '100%',
hiddengrid: false
});
jQuery("#theGrid").jqGrid('navGrid', '#gridPager', { "edit": false, "add": false, "del": false, "search": false, view: false });
$("#theGrid").jqGrid('inlineNav', '#gridPager',
{
add: true,
addicon: "ui-icon-plus",
save: true,
saveicon: "ui-icon-disk",
cancel: true,
cancelicon: "ui-icon-cancel",
"refresh": true,
"view": true,
addoptions: {
url: '/Student/Create'
},
addParams: {
addRowParams: {
url: '/Student/Create',
mtype:"POST",
keys: true,
oneditfunc: function (rowid) {
alert("new row with rowid=" + rowid + " are added.");
}
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [true, ''];
} else {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [false, response.responseText];
}
}
}
});
public JsonResult Grid(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
IEnumerable<Student> StudentData = db.Students.ToList();
int totalRecords = StudentData.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
StudentData = StudentData.OrderByDescending(s => s.Id);
StudentData = StudentData.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
StudentData = StudentData.OrderBy(s => s.Id);
StudentData = StudentData.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = StudentData
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpPost]
[ValidateAntiForgeryToken]
public string Create([Bind(Exclude = "Id")] Student student)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Edit(Student student)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
//Deletes the product
public string Delete(int Id)
{
Student student = db.Students.Find(Id);
db.Students.Remove(student);
db.SaveChanges();
return "Deleted successfully";
}
控制器:
jQuery("#theGrid").jqGrid({
url: '/Student/Grid',
datatype: "json",
colNames: ['Id', 'Firstname', 'Middlename', 'Lastname', 'Birthdate', 'Birthplace', 'State', 'Nationality', 'Religion', 'Ishandicaped ?', 'Actions'],
colModel: [
{ key: true, name: 'Id', sortable: true, resize: true, align: "center", hidden: true },
{ key: false, name: 'FirstName', index: 'FirstName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'MiddleName', index: 'MiddleName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'LastName', index: 'LastName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'Birthdate', index: 'Birthdate', editable: true, align: "center", editrules: { required: true }, formatter: 'date', editoptions: { dataInit: function (el) { setTimeout(function () { $(el).datepicker(); }, 200); } } },
{ key: false, name: 'Birthplace', index: 'Birthplace', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'State', index: 'State', editable: true, align: "center", edittype: "select", editoptions: { value: "GJ:Gujarat;MH:Maharashtra;DL:Delhi;BNG:Banglore;RJ:Rajasthan" }, editrules: { required: true } },
{ key: false, name: 'Nationality', index: 'Nationality', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'Religion', index: 'Religion', editable: true, align: "center", editrules: { required: true } },
{
key: false, name: 'IsHandicaped', index: 'IsHandicaped', editable: true, align: "center", edittype: "checkbox", editoptions: { value: "True:False" }
},
{
key: false,
name: 'Actions',
index: 'tax',
width: 80,
align: "center",
formatter: 'actions',
formatoptions: {
keys: true,
delOptions: { url: '/Student/Delete' }
}
}
],
rowNum: 10,
rownumbers: true,
autowidth: true,
rowList: [5, 10, 20],
pager: '#gridPager',
sortname: 'invdate',
viewrecords: true,
sortorder: "acc",
altRows: true,
delicon: 'glyphicon glyphicon-trash',
altclass: 'table table-striped',
jsonReader: {
repeatitems: false
},
editurl: '/Student/Edit',
mtype:"PUT",
height: '100%',
hiddengrid: false
});
jQuery("#theGrid").jqGrid('navGrid', '#gridPager', { "edit": false, "add": false, "del": false, "search": false, view: false });
$("#theGrid").jqGrid('inlineNav', '#gridPager',
{
add: true,
addicon: "ui-icon-plus",
save: true,
saveicon: "ui-icon-disk",
cancel: true,
cancelicon: "ui-icon-cancel",
"refresh": true,
"view": true,
addoptions: {
url: '/Student/Create'
},
addParams: {
addRowParams: {
url: '/Student/Create',
mtype:"POST",
keys: true,
oneditfunc: function (rowid) {
alert("new row with rowid=" + rowid + " are added.");
}
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [true, ''];
} else {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [false, response.responseText];
}
}
}
});
public JsonResult Grid(string sidx, string sord, int page, int rows)
{
int pageIndex = Convert.ToInt32(page) - 1;
int pageSize = rows;
IEnumerable<Student> StudentData = db.Students.ToList();
int totalRecords = StudentData.Count();
var totalPages = (int)Math.Ceiling((float)totalRecords / (float)rows);
if (sord.ToUpper() == "DESC")
{
StudentData = StudentData.OrderByDescending(s => s.Id);
StudentData = StudentData.Skip(pageIndex * pageSize).Take(pageSize);
}
else
{
StudentData = StudentData.OrderBy(s => s.Id);
StudentData = StudentData.Skip(pageIndex * pageSize).Take(pageSize);
}
var jsonData = new
{
total = totalPages,
page,
records = totalRecords,
rows = StudentData
};
return Json(jsonData, JsonRequestBehavior.AllowGet);
}
[HttpPost]
[ValidateAntiForgeryToken]
public string Create([Bind(Exclude = "Id")] Student student)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.Students.Add(student);
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
public string Edit(Student student)
{
string msg;
try
{
if (ModelState.IsValid)
{
db.Entry(student).State = EntityState.Modified;
db.SaveChanges();
msg = "Saved Successfully";
}
else
{
msg = "Validation data not successfull";
}
}
catch (Exception ex)
{
msg = "Error occured:" + ex.Message;
}
return msg;
}
//Deletes the product
public string Delete(int Id)
{
Student student = db.Students.Find(Id);
db.Students.Remove(student);
db.SaveChanges();
return "Deleted successfully";
}
publicjsonresult网格(字符串sidx、字符串sord、int页、int行)
{
int pageIndex=Convert.ToInt32(第页)-1;
int pageSize=行;
IEnumerable StudentData=db.Students.ToList();
int totalRecords=StudentData.Count();
var totalPages=(int)数学上限((float)totalRecords/(float)行);
if(sord.ToUpper()=“DESC”)
{
StudentData=StudentData.OrderByDescending(s=>s.Id);
StudentData=StudentData.Skip(页面索引*页面大小)。Take(页面大小);
}
其他的
{
StudentData=StudentData.OrderBy(s=>s.Id);
StudentData=StudentData.Skip(页面索引*页面大小)。Take(页面大小);
}
var jsonData=new
{
总计=总页数,
页
记录=总记录,
行=学生数据
};
返回Json(jsonData、JsonRequestBehavior.AllowGet);
}
[HttpPost]
[ValidateAntiForgeryToken]
创建公共字符串([Bind(Exclude=“Id”)]Student)
{
串味精;
尝试
{
if(ModelState.IsValid)
{
db.Students.Add(学生);
db.SaveChanges();
msg=“保存成功”;
}
其他的
{
msg=“验证数据未成功”;
}
}
捕获(例外情况除外)
{
msg=“出现错误:”+ex.消息;
}
返回味精;
}
公共字符串编辑(学生)
{
串味精;
尝试
{
if(ModelState.IsValid)
{
db.Entry(student.State=EntityState.Modified;
db.SaveChanges();
msg=“保存成功”;
}
其他的
{
msg=“验证数据未成功”;
}
}
捕获(例外情况除外)
{
msg=“出现错误:”+ex.消息;
}
返回味精;
}
//删除产品
公共字符串删除(int-Id)
{
Student=db.Students.Find(Id);
db.student.Remove(学生);
db.SaveChanges();
返回“删除成功”;
}
当我内联添加新行并单击save时,每次它调用控制器的edit方法。谁能告诉我如何触发控制器的create方法在数据库中插入新记录。提前谢谢
如何调用控制器的这个创建方法在数据库中插入新行
您应该始终编写您使用的jqGrid的分支和版本。您使用哪个版本的ASP.NET MVC?此外,我严格建议您发布简单代码,而不是发布当前代码。您发布的
colModel
有11列。所有栏目都与问题相关吗?是否可以将所有操作简化为例如Id
、FirstName
、LastName
和Actions
?[ValidateAntiForgeryToken]
和[Bind(Exclude=“Id”)]
属性在创建中确实是必需的吗?你目前的主要问题是什么?是否将调用Create
?是否将student
数据填充?您使用afterSubmit
回调addParams
。您得到的addRow
支持这样的回调。见文件。calback存在于表单编辑中,而不存在于内联编辑中。您在afterSubmit
回调中测试response.responseText==“”
,但服务器(Create
action)始终返回非空字符串。你的目标是什么?您试图实现什么?如果您有一些问题,请描述清楚。您能通过编写代码片段来解释我吗?我正在使用JqGrid 4.4.4进行编辑/删除,我使用了格式化程序:“操作”,它看起来工作得很好。但现在我正在网格和数据库中实现内联添加行。抱歉,为您编写代码片段太多了。如果将调用Edit
操作,则可以向其添加oper
参数(Edit(stringoper,Student-Student)
)并删除url:'/Student/Create'
。您将看到,Edit
操作将被调用,oper
将是“添加”
、“编辑”
或“删除”
(如果您要共享editurl
,最后一个操作也将被删除)。不建议使用旧的4.4.4。如果您使用旧的jQuery.jqGrid
package从NuGet安装了它,那么您应该卸载它并安装免费的jqGrid
包。确切地说,我只在旧版本中遇到了这个问题,但它是项目要求。您应该始终编写您使用的jqGrid分支以及在哪个版本中。您使用哪个版本的ASP.NET MVC?此外,我严格建议您发布简单代码,而不是发布当前代码。您发布的colModel
有11列。所有栏目都与问题相关吗?是否可以将所有操作简化为例如Id
、FirstName
、LastName
和Actions
?[ValidateAntiForgeryToken]
和[Bind(Exclude=“Id”)]
属性在创建中确实是必需的吗?你目前的主要问题是什么?是否将调用Create
?是否将student
数据填充?您使用afterSubmit
回调addParams
。您得到的addRow
支持这样的回调。见文件。calback存在于表单编辑中,而不存在于内联编辑中。您在afterSubmit
回调中测试response.responseText==“”
,但服务器(Create
action)始终返回非空字符串。你的目标是什么?您试图实现什么?如果你有