Create Jqgrid pass value from datatable and change column names dynamically - asp.net-mvc-3

I want to create jqgrid by passing value from Datatable as I have multiple tables ,based on that I need to change colomn names dynamically,in asp.net mvc.

Hi after working hard on it finally i have got a solution.
<table id="tableDetails1" cellpadding="0" cellspacing="0">
<tr><td></td></tr></table>
<div id="pager" style="text-align: center"></div>
Jqgrid and javascript function
<script type="text/javascript">
$(document).ready(function () {
// $("#tableDetails1").GridUnload();
CreateColumnDetails();
});
function getData() {
debugger;
$.ajax({
url: '#Url.Action("TableDetails", "TableInfo")',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
debugger;
var obj = $.parseJSON(result);
resultData = JSON.parse(result);
$(resultData).each(function (e) {
$("#tableDetails1").addRowData(e, this);
});
}
});
}
function CreateColumnDetails() {
debugger;
$.ajax({
url: '#Url.Action("GetColumnDetails", "TableInfo")',
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (result) {
var colName = JSON.parse(result);
debugger;
var colModels = BuildColumnModel(colName);
$("#tableDetails1").jqGrid({
url: '#Url.Action("GetColumnDetails", "TableInfo")',
datatype: 'json',
colNames: colName,
colModel: colModels
})
}
});
getData();
}
function CreateGrid(result) {
debugger;
$("#tableDetails1").jqGrid({
url: '#Url.Action("TableDetails", "TableInfo")',
datatype: 'json',
mtype: 'Get',
pager: $('#pager'),
rowNum: 5,
gridview: true,
rowList: [5, 10, 20, 30],
height: '100%',
viewrecords: true,
caption: 'Table Details ',
emptyrecords: 'No Records found',
jsonReader: {
root: function (rows) {
debugger;
return typeof rows === "string" ? $.parseJSON(rows) : rows;
},
page: 'page',
total: 'total',
records: 'records',
repeatitems: false,
id: "0"
},
autowidth: true,
multiselect: false,
loadError: function (jqXHR, textStatus, errorThrown) {
debugger;
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
}
}).navGrid('pager', { edit: false, add: false, del: false });
}
function BuildColumnModel(result) {
// var uFields = result.split(',');
var uFields = result;
var columns = [];
for (var i = 0; i < uFields.length ; i++) {
if (uFields[i].indexOf('Id') > -1) {
columns.push({ name: uFields[i], index: uFields[i], key: true });
//columns.push({ 'name': name, 'index': name, key: true});
}
// else if (uFields[i].indexOf('Name') > -1) {
else if(uFields[i].length>-1){
columns.push({ name: uFields[i], index: uFields[i]})
// columns.push({ 'name': name, 'index': name });
}
//else if (uFields[i].length > -1) {
// columns.push({ name: uFields[i], index: uFields[i]})
// //columns.push({ 'name': name, 'index': name, key: true });
//}
}
return columns;
}
</script>
Controllers
**Httppost method adding rows dynamically
[HttpPost]
public ActionResult TableDetails(int? id, DataTable dt)
{
dt = new DataTable();
dt = GetTableDetails(id);
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
serializer.Serialize(col.ColumnName);
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return Json(serializer.Serialize(rows), JsonRequestBehavior.AllowGet);
}
Column Details in string format
[HttpPost]
public ActionResult GetColumnDetails(int ? id, DataTable dt)
{
dt = GetTableDetails(1);
// id = (int)Session["id"] ;
// dt = GetTableDetails(id);
string[] columnNames = dt.Columns.Cast<DataColumn>()
.Select(x => x.ColumnName)
.ToArray();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(columnNames), JsonRequestBehavior.AllowGet);
}

Related

JsGrid Sorting not working

Following is part of my JsGrid code, which I think something is missing in order for me to sort my data like any other examples on Fiddle.
autoload: true,
inserting: false,
editing: false,
paging: true,
pageIndex: 1,
pageSize: 5,
pageLoading: true,
autoload: true,
filter: true,
sorting: true,
controller: {
loadData: function(filter) {
return $.ajax({
type: "GET",
url: BASE_URL,
data: filter,
dataType: "json",
cache: false
});
},
},
I have tried with sorting:"number".
Below logic of sorting on the basis of number
$("#Grid2").jsGrid({
height: "auto",
width: "100%",
filtering: false,
editing: false,
sorting: true,
paging: true,
autoload: true,
inserting: false,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(filter) {
var d = $.Deferred();
$.ajax({
cache: false,
type: 'GET',
url: "http://" + servername + ":" + portnumber + "/api,
data: filter,
dataType: "json",
success: function(data) {
filteredData = $.grep(data, function(item) {
//filtering logic
;
});
d.resolve(filteredData);
testdata = JSON.stringify(data);
$("#Grid2").jsGrid("sort", 1);
HistoricData = data;
},
error: function(e) {
console.log(e);
console.log(e.responseText);
var errorMsg = e.responseText;
var msg = errorMsg + " for this particular combination";
showError(msg);
$("#displayingHistoryValues").hide();
$("#ExportGrid2").hide();
$("#Grid2").hide();
d.resolve();
}
});
return d.promise();
}
},
fields: [{
title: "Value",
name: "MeasureValue",
type: "number",
width: "5%",
css: "custom-field",
sorting: true,
itemTemplate: function(value, item) {
if (item.MeasureValue != null && item.MeasureValue != '' && item.MeasureValue.trim().length > 0) {
var mesval = FormatValeur(item.MeasureUnit, item.MeasureValue);
return "<div>" + mesval + "</div>";
}
}
}, {
type: "control",
editButton: false,
deleteButton: false,
width: "5%"
}]
})
Another way to sort, get the filteredData or loaded data
and call onRefresing of JSGrid .
Way to sort JS grid on column after grid load :
onRefreshing: function (args) {
fundCodeList = [];
jsonNumLst = [];
jsonNANLst = [];
if(this._visibleFieldIndex(this._sortField) == -1
|| this._visibleFieldIndex(this._sortField)==1){
$.each(filteredData, function(inx, obj) {
if($.isNumeric(obj.fundCode)){
jsonNumLst.push(obj);
}else{
jsonNANLst.push(obj);
}
});
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
jsonNumLst.sort(sortByNumFCAsc);
jsonNANLst.sort(sortByNANFCAsc);
}else if(this._sortOrder == 'desc'){
jsonNANLst.sort(sortByNANFCDesc);
jsonNumLst.sort(sortByNumFCDesc);
}
if(jsonNumLst.length>0 || jsonNANLst.length>0){
filteredData = [];
if(this._sortOrder == undefined || this._sortOrder == 'asc'){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNumLst.length){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
}
}else if(this._sortOrder == 'desc'){
$.each(jsonNANLst, function(inx, obj) {
filteredData.push(obj);
});
if(filteredData.length == jsonNANLst.length){
$.each(jsonNumLst, function(inx, obj) {
filteredData.push(obj);
});
}
}
}
if((filteredData.length>0) && filteredData.length==(jsonNumLst.length+jsonNANLst.length)){
$("#measureImportGrid3").data("JSGrid").data = filteredData;
//isSortGrid = false;
//saveEffectControlData = $('#saveEffectiveControlGrid').jsGrid('option', 'data');
}
}
//Ascending order numeric
function sortByNumFCAsc(x,y) {
return x.fundCode - y.fundCode;
}
//Ascending order nonnumeric
function sortByNANFCAsc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((x.fundCode > y.fundCode) ? 1 : -1 ));
}
//Descending order numeric
function sortByNANFCDesc(x,y) {
return ((x.fundCode == y.fundCode) ? 0 : ((y.fundCode > x.fundCode) ? 1 : -1 ));
}
//Descending order non-numeric
function sortByNumFCDesc(x,y) {
return y.fundCode - x.fundCode;
}
}

Jqgrid with mvc4

I want to create dynamic Jqgrid at runtime. I have made tow methods as
public ActionResult getdata( List<UserModel> lst)
{
UserModel usermodel = new UserModel();
UserService uservice = new UserService();
//return View(db.VideoModels.OrderByDescending(v => v.VideoId).ToPagedList(page, 3));
string[] columnNames = (string[])TempData["columnname"];
lst = new List<UserModel>();
lst = uservice.GetAllUsers();
JavaScriptSerializer serializer = new JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (var dr in lst)
{
row = new Dictionary<string, object>();
rows.Add(row);
}
return Json(serializer.Serialize(lst), JsonRequestBehavior.AllowGet);
}
public ActionResult GetColumnDetails( List<UserModel> lst)
{
UserModel usermodel = new UserModel();
UserService uservice = new UserService();
lst = new List<UserModel>();
lst = uservice.GetAllUsers();
var listOfStrings = new List<string>();
string[] colNames = listOfStrings.ToArray();
string[] columnNames = (from t in typeof(PrTblUsers).GetProperties() select t.Name).ToArray();
JavaScriptSerializer serializer = new JavaScriptSerializer();
return Json(serializer.Serialize(colNames= columnNames), JsonRequestBehavior.AllowGet);
}
getcolumdetail is for getting column name and get data is for getting data.
div class="row">
<div id="content" style="margin-left:15px !important;">
<table id="datacopyProject"></table>
<div id="datacopy_pagerProject"></div>
#*<table id="datacopyfilter"></table>
<div id="datacopy_pagerfilter"></div>*#
</div>
</div>
<script type="text/javascript" id="getdata">
$(document).ready(function () {
var item = [];
//creating the dyanamic colmodel
$("#datacopyProject").jqGrid('GridUnload');
$.ajax(
{
type: "POST",
url: '/Test/GetColumnDetails',
//data: { tid: data },
dataType: "json",
success: function (result) {
var colModels = BuildColumnModel(JSON.parse(result));
//console.log(JSON.stringify(result));
//var obj = jQuery.parseJSON(result);
//var columnData = result.mypage,
item= getData();
//alert(item);
jQuery("#datacopyProject").jqGrid({
colNames: item,
colModel: colModels,
autowidth:true,
caption: "User List",
pager: jQuery('#datacopy_pagerProject'),
rowNum: 3,
viewrecords: true,
rowList: [5, 10, 20, 50],
viewrecords: true,
jsonReader: {
repeatitems: false,
root: function (obj) { return obj; },
page: function (obj) { return $("#datacopyProject").jqGrid('getGridParam', 'page'); },
total: function (obj) { return Math.ceil(obj.length / $("#datacopyProject").jqGrid('getGridParam', 'rowNum')); },
records: function (obj) { return obj.length; }
},
gridComplete: function () {
},
loadComplete: function (data) { }
})
},
loadonce:true,
error: function (x, e) {
alert(x.readyState + " " + x.status + " " + e.msg);
}
});
//setTimeout(function () { $("#datacopyProject").jqGrid('setGridParam', { datatype: 'json' }); }, 500);
//binding the data to dyanamic colmodel
function getData()
{
$.ajax({
url: '/Test/getdata',
type: "POST",
datatype: "json",
//data: { userid: data },
async: false,
success: function (response) {
var resultData = JSON.parse(response);
//var data = resultData.slice(1, resultData.length - 1);
//var json = JSON.stringify(data);
//console.log(resultData);
////var resultData = JSON.parse(response);
for (var i = 0; i <= resultData.length; i++)
item = $("#datacopyProject").jqGrid('addRowData', i + 1, datacopyProject[i]);
//$(resultData).each(function (e) {
// $("#datacopyProject").addRowData(e, this);
//});
}
});
}
});
function BuildColumnModel(result) {
debugger;
// var uFields = result.split(',');
var uFields = result;
var columns = [];
for (var i = 0; i < uFields.length ; i++) {
if (uFields[i].indexOf('Id') > -1) {
columns.push({ name: uFields[i], index: uFields[i], key: true });
//columns.push({ 'name': name, 'index': name, key: true});
}
// else if (uFields[i].indexOf('Name') > -1) {
else if (uFields[i].length > -1) {
columns.push({ name: uFields[i], index: uFields[i] })
// columns.push({ 'name': name, 'index': name });
}
//else if (uFields[i].length > -1) {
// columns.push({ name: uFields[i], index: uFields[i]})
// //columns.push({ 'name': name, 'index': name, key: true });
//}
}
return columns;
}
I am getting the column value in jQgrid but not getting the rows.
You can use the solution explained in this post, and return from the controller a ViewBag with these variables joined:
var jsonGrid = jQuery.parseJSON('#Html.Raw(ViewBag.YourGridVariableInJson)');

A grid containing href link links to all the rows instead of a particular row

I have made a grid in which the last column contains a link resend. This link resends the mail to the party mentioned in the row. when I click on that link it resend the mail to all the parties in the grid instead of that particular row.. Below is my code
$(document).ready(
function(){
var lastselsignStatusGrid ;
var signStatusGridurl = $('#signatureStatus_ctxPath').val() + '/rest/retrieveSignStatus';
var maintainsignStatusGridurl = $('#signatureStatus_ctxPath').val() + '/rest/maintainSignStatus';
jQuery('#signStatusGrid').jqGrid({
url: signStatusGridurl,
datatype: "json",
mtype: 'GET',
altRows:true,
loadonce: true,
colNames:['Name','Role','Signature status','Due Date','Signed Date','Email','EmailId','PartyId'],
colModel:[
{name: 'name',index: 'name',sortable:true,search:true,sorttype: 'text', searchoptions:{sopt:['eq','ne','bw','cn']}},
{name: 'role',index: 'role',sortable:true,search:true,sorttype: 'text', searchoptions: {sopt:['eq','ne','bw','cn']}},
{name: 'signed',index: 'signed',sortable:false,search:false,sorttype: 'text'},
{name: 'dueDate',index: 'dueDate',formatter: 'date', formatoptions: {"srcformat":"m/d/Y","newformat":"m/d/Y"}, unformat: unformat, sortable:false,search:false,sorttype: 'date'},
{name: 'signedDate',index: 'signedDate',sortable:false,search:false,sorttype: 'text'},
{name: 'resend',index: 'resend',formatter: customLinksignStatusresend, unformat: unformat, sortable:false,search:false,sorttype: 'text'},
{name: 'emailAddress',index: 'emailAddress',hidden:true },
{name: 'partyId',index: 'partyId',hidden:true}
],
rowNum:10,
rowList:[10,20,30],
multiselect: false,
viewrecords: true,
emptyrecords: "No record present",
imagepath: "js/themes/redmond/images",
autowidth: true,
caption:''
});
function customLinksignStatusresend(cellValue, options, rowObject){
if (rowObject[2] == "Complete") {
return "";
} else{
//return rowObject[5];
//return '' + "Resend";
return '<a href="#Test">' + cellValue + '<a>';
}
}
$(document).delegate('#signStatusGrid .jqgrow td a[href="#Test"]', 'click', function ()
{
var localGridData = $("#signStatusGrid").jqGrid('getGridParam','data');
var postData = JSON.stringify(localGridData);
var rowDetails="";
var selectedRows = $('#signStatusGrid').jqGrid('getGridParam', 'data');
var rowsArray = new Array();
var rowId = '';
for(var i=0;i<localGridData.length;i++)
{
var rowData = localGridData[i];
var emailAddr = rowData.emailAddress;
var partyId = rowData.partyId;
rowDetails += partyId+":" +emailAddr+ ',';
$.ajax({
url: $('#signatureStatus_ctxPath').val()+'/rest/resendEmail?partyId='+ partyId,
datatype : "json",
contentType: "application/json; charset=utf-8",
type:"POST",
error : function(xhr, textStatus, errorThrown) {
alert(errorThrown);
},
success : function(response, textStatus, xhr) {
alert("email resent successfully");
}
});
HideLayer();
}
});
You are looping through all the rows in the grid which is why the mail is being sent to all the recipients.
The easy way to do what you are trying to achieve would be to use the onCellSelect function of jqGrid to send mail to the particular Row emailId. You can add additional conditions so that it gets called only when the link is clicked.
onCellSelect: function (id, iCol, cellContent, e) {
if (iCol == 'resend') {
var emailAddr = $('#signStatusGrid').getCell(id, 'emailAddress');
var partyId = $('#signStatusGrid').getCell(id, 'partyId');
var rowDetails += partyId + ":" + emailAddr + ',';
$.ajax({
url: $('#signatureStatus_ctxPath').val() + '/rest/resendEmail?partyId=' + partyId,
datatype: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
},
success: function (response, textStatus, xhr) {
alert("email resent successfully");
}
});
}
},
Another alternate solution seems to be to create a function with sending mail and setting a link which will call the same with respective partyId in the gridComplete function of jqGrid :
gridComplete: function () {
var ids = jQuery("#signStatusGrid").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
var partyId = $('#signStatusGrid').getCell(ids[i], 'partyId');
var be = "<a href='#Test' onclick='sendMail(" + partyId + ");' >View Contract</a>";
jQuery("#signStatusGrid").jqGrid('setRowData', ids[i], {
editct: be
});
}
},
var sendMail(partyId) {
$.ajax({
url: $('#signatureStatus_ctxPath').val() + '/rest/resendEmail?partyId=' + partyId,
datatype: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
},
success: function (response, textStatus, xhr) {
alert("email resent successfully");
}
});
}

jqGrid Setting id of new added Row intoGrid

jQuery.extend(
jQuery.jgrid.edit, {
ajaxEditOptions: { contentType: "application/json" }, //form editor
reloadAfterSubmit: true
// afterSubmit: function (response, postdata) {
// return [true, "", $.parseJSON(response.responseText).d];
//}
});
$.extend($.jgrid.defaults, {
datatype: 'json',
ajaxGridOptions: { contentType: "application/json" },
ajaxRowOptions: { contentType: "application/json", type: "POST" },
//row inline editing
serializeGridData: function(postData) { return JSON.stringify(postData); },
jsonReader: {
repeatitems: false,
id: "0",
cell: "",
root: function(obj) { return obj.d.rows; },
page: function(obj) { return obj.d.page; },
total: function(obj) { return obj.d.total; },
records: function(obj) { return obj.d.records; }
}
});
$("#grantlist").jqGrid({
url: 'webservice.asmx/GetGrant',
colNames: ['ID', 'Name', 'Title'],
colModel: [
{ name: 'ID', width: 60, sortable: false },
{ name: 'name', width: 210, editable: true },
{ name: 'title', width: 210, editable: true }
],
serializeRowData: function(data) {
var params = new Object();
params.ID = 0;
params.name = data.name;
params.title = data.title;
return JSON.stringify({ 'passformvalue': params, 'oper': data.oper, 'id': data.id });
},
mtype: "POST",
sortname: 'ID',
rowNum: 4,
height: 80,
pager: '#pager',
editurl: "webservice.asmx/ModifyGrant"
});
$("#grantlist").jqGrid('navGrid', '#pager', { add: false, edit: false, del: false, refresh: false, search: false });
$("#grantlist").jqGrid('inlineNav', '#pager');
//this is my server code
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public JQGrid<GrantComittee> GetGrantComittee(int? page, int? rows, string sidx, string sord, bool _search)
{
JQGrid<GrantComittee> jqgrid = new JQGrid<GrantComittee>();
List<GrantComittee> data = GetGComittee();
jqgrid.records = data.Count; //total row count
jqgrid.total = (int)Math.Ceiling((double)data.Count / (double)rows); //number of pages
jqgrid.page = page.Value;
//paging
data = data.Skip(page.Value * rows.Value - rows.Value).Take(rows.Value).ToList();
foreach(GrantComittee i in data)
jqgrid.rows.Add(i);
return jqgrid;
}
[WebMethod(EnableSession = true), ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public int ModifyGrantComittee(GrantComittee passformvalue, string oper, string id)
{
if (String.Compare(id, "_empty", StringComparison.Ordinal) == 0 ||
String.Compare(oper, "add", StringComparison.Ordinal) == 0)
{
GrantComittee data = new GrantComittee();
List<GrantComittee> set = new List<GrantComittee>();
set = (List<GrantComittee>)Session["grantcomittee"];
data = passformvalue;
data.ID = set.Max(p => p.ID) + 1;
set.Add(data);
Session["grantcomittee"] = set;
return data.ID;
}
else if (String.Compare(oper, "edit", StringComparison.Ordinal) == 0)
{
// TODO: modify the data identified by the id
return 0;
}
else if (String.Compare(oper, "del", StringComparison.Ordinal) == 0)
{
// TODO: delete the data identified by the id
return 0;
}
return 0;
}
I am using JqGrid to retrieve and add new records to database. So far i have been able to retrieve and add new items to the DB, I am using "json". I do get in the response {"d": "5"} for the id of the newly created row in the DB. However the new id does not display in the grid.
How can I update that value to new added row?
In the most cases you don't need to do anything because of default setting reloadAfterSubmit: true. It means that the full grid will be reloaded from the server after the user add new row or modify an existing one.
If you want use reloadAfterSubmit: false setting and the server returns the id of the new created row in the response you need implement afterSubmit callback function which will decode the server response and return it for the usage of by jqGrid. The corresponding code could be about the following:
afterSubmit: function (response, postdata) {
return [true, "", $.parseJSON(response.responseText).d];
}
You can define the callback by overwriting the default parameters $.jgrid.edit (see here and here).
I am using 'inlinNav' and after adding a new row i was not getting the grid to reload. The solution I found was to add parametes to the 'inlineNav' declaration. So I end up with the code i am providing as reference:
$("#grantlist").jqGrid('inlineNav', '#pager', { addParams: { position: "last", addRowParams: {
"keys": true, "aftersavefunc": function() { var grid = $("#grantlist"); reloadgrid(grid); }
}
}, editParams: { "aftersavefunc": function() { var grid = $("#grantlist"); reloadgrid(grid); } }
});
function reloadgrid(grid) {
grid.trigger("reloadGrid");
}
I was using more than one grid that is why i pass a grid parameter to the reload function.

Dynamic Columns in jqGrid

I've tried with limited success to get dynamic columns to work with jqGrid. Limited in that I can control the column names and formatting from the controller. But when I do this I can't get the data in.
Do you have a small sample solution that shows the controller code for the two calls.
you can actually bind the column as normal but you can show/hide them at runtime using jquery. for example i have to show link column in jqgrid for admin user and for normal users that column needs to be hidden so implement this in following way.
$("#grid").showCol("Link");
$("#grid").hideCol("Link");
$("#grid").trigger("reloadGrid");
JQGrid1.Columns.FromDataField(ColumnName).Visible = false;
JQGrid1.Columns.FromDataField(ColumnName).HeaderText = "Sample";
JQGrid(action, caption, 920, 400, loadtext);
function columnsData(Data) {
var str = "[";
for (var i = 0; i < Data.length; i++) {
str = str + "{name:'" + Data[i] + "', index:'" + Data[i] + "', editable: true}";
if (i != Data.length - 1) {
str = str + ",";
}
}
str = str + "]";
return str;
}
function JQGrid(action, caption, width, height, loadtext) {
var grid = $("#tblGrid");
var lastsel;
var editurl = '/PayInvoice/GridSave';
$.ajax({
url: action,
dataType: "json",
mtype: 'POST',
beforeSend: function () {
$("#dvloading").show();
},
success: function (result) {
if (result) {
if (!result.Error) {
var colData = columnsData(result.column);
colData = eval('{' + colData + '}');
grid.jqGrid('GridUnload');
grid.jqGrid({
url: action,
datatype: 'json',
mtype: 'POST',
colModel: colData,
colNames: result.column,
// multiselect: true,
width: width,
height: height,
rowNum: 20,
rowList: [20, 40, 60],
loadtext: loadtext,
pager: '#tblGridpager',
sortorder: "asc",
viewrecords: true,
gridview: true,
altRows: true,
cellEdit: true,
cellsubmit: "remote",
cellurl: '/PayInvoice/GridSavecell',
beforeSubmitCell: function (id, cellname, value, iRow, iCol) {
objedit(id, cellname, value);
return { id: id, cellname: cellname, value: value, iRow: iRow, iCol: iCol };
},
afterSaveCell: function (id, cellname, value, iRow, iCol) {
objedit(id, cellname, value);
return { id: id, cellname: cellname, value: value, iRow: iRow, iCol: iCol };
},
caption: caption
});
}
}
},
error: function (xhr, ajaxOptions, thrownError) {
if (xhr && thrownError) {
alert('Status: ' + xhr.status + ' Error: ' + thrownError);
}
}, complete: function () {
$("#dvloading").hide();
}
});
}
function objedit(id, cellname, value) {
var flag = 0;
for (var i = 0; i < index; i++) {
if (obj[i][0] == id && obj[i][1] == cellname) {
obj[i] = [id, cellname, value]
flag++;
}
}
if (flag == 0) {
obj[index] = [id, cellname, value];
index++;
}
}
Here we go;
$("#datagrid").jqGrid({
//url: "user.json",
//datatype: "json",
datatype: "local",
data: dataArray,
colNames:getColNames(dataArray[0]),
colModel:getColModels(dataArray[0]),
rowNum:100,
loadonce: true,
pager: '#navGrid',
sortname: 'SongId',
sortorder: "asc",
height: "auto", //210,
width:"auto",
viewrecords: true,
caption:"JQ GRID"
});
function getColNames(data) {
var keys = [];
for(var key in data) {
if (data.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys;
}
function getColModels(data) {
var colNames= getColNames(data);
var colModelsArray = [];
for (var i = 0; i < colNames.length; i++) {
var str;
if (i === 0) {
str = {
name: colNames[i],
index:colNames[i],
key:true,
editable:true
};
} else {
str = {
name: colNames[i],
index:colNames[i],
editable:true
};
}
colModelsArray.push(str);
}
return colModelsArray;
}

Resources